so I want to add an option to delete a particular entry in a list, so I added an Image view into my list's adapter. But for some reason, when I try to create the list in my app now, it crashes. This is the error line :
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ImageView
Here is the code for my list adapter :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskAdapter extends ArrayAdapter<subtask> {
private final Context context;
private ArrayList<subtask> values;
public SubtaskAdapter(Context context, ArrayList<subtask> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.subtask_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = convertView.findViewById(R.id.ivPri);
ImageView ivTime = convertView.findViewById(R.id.ivTime);
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh()) {
ivPri.setImageResource(R.drawable.priority_high);
} else if (values.get(position).isPriMed()) {
ivPri.setImageResource(R.drawable.priority_med);
} else if (values.get(position).isPriLow()) {
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore()) {
ivTime.setImageResource(R.drawable.time_symbol_more);
} else if (values.get(position).isTimeMed()) {
ivTime.setImageResource(R.drawable.time_symbol_med);
} else if (values.get(position).isTimeLess()) {
ivTime.setImageResource(R.drawable.time_symbol_less);
}
// Delete button for subtasks
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.remove(position);
notifyDataSetChanged();
}
});
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(subtask newSubTask){
ArrayList<subtask> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
This is the xml code for the list item :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ivDelete"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="16dp"
android:background="#color/white"
android:clickable="true"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:clickable="true"
app:srcCompat="#drawable/delete" />
<TextView
android:id="#+id/tvSubtaskName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="subtask_name"
android:textColor="#color/black"
android:textSize="15sp" />
<ImageView
android:id="#+id/ivPri"
android:layout_width="0dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/priority_high" />
<ImageView
android:id="#+id/ivTime"
android:layout_width="0dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/time_symbol_more" />
</LinearLayout>
You are trying to reference a LinearLayout as an ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ivDelete"
...
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
Do you see the ids here?
Just replace this last line with the following:
LinearLayout ivDelete = convertView.findViewById(R.id.ivDelete);
Your issue is here:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ivDelete"
and in your getView()
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
Use:
ImageView ivDelete = convertView.findViewById(R.id.imageView);
since in your layout:
<ImageView
android:id="#+id/imageView"
app:srcCompat="#drawable/delete"
yet another answer with fastest fix: replace id of your deleting ImageView, from:
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
to
ImageView ivDelete = convertView.findViewById(R.id.imageView);
btw. clean up your resources naming, currently your whole row have ivDelete id
Related
Previously I had crash issues due to the wrong reference to the resource files. Fixed that issue and updated this thread with the logical error that I am getting.
I am new to android and currently learning custom classes and adapter. While working I am facing a problem which is the listview shows the first arraylist item only.
I have attached the codes of the required files as well.
Working Activity
package np.com.shresthakiran.tourswoniga;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class KhowpaActivity extends AppCompatActivity {
ListView lvHeritageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_heritage);
lvHeritageList = findViewById(R.id.lvHeritage);
ArrayList<Heritages> heritageAryList = new ArrayList<>();
heritageAryList.add(new Heritages(R.drawable.ic_launcher_background,"Ngatapol", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Dattatreya", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Lu dhwakha", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "55 jhyale Durbar", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Taleju Bhawani", "Lyaaku"));
HeritageAdapter heritageAdapter = new HeritageAdapter(KhowpaActivity.this, R.layout.heritages_row, heritageAryList);
lvHeritageList.setAdapter(heritageAdapter);
}
}
Custom Adapter
package np.com.shresthakiran.tourswoniga;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HeritageAdapter extends ArrayAdapter<Heritages> {
private Context mContext;
private int mResource;
public HeritageAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Heritages> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater =LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
ImageView ivHeritageImage = convertView.findViewById(R.id.ivHeritage);
TextView tvHeritageName = convertView.findViewById(R.id.tvHeritageName);
TextView tvHeritageAddress = convertView.findViewById(R.id.tvHeritageAddress);
ivHeritageImage.setImageResource(getItem(position).getmImageResourceId());
tvHeritageName.setText(getItem(position).getmHeritageName());
tvHeritageAddress.setText(getItem(position).getmHeritageAddress());
return convertView;
}
}
Object Class
package np.com.shresthakiran.tourswoniga;
public class Heritages {
private int mImageResourceId;
private String mHeritageName;
private String mHeritageAddress;
public Heritages(int heritageImageResourceId, String heritageName, String heritageAddress) {
this.mImageResourceId = heritageImageResourceId;
this.mHeritageName = heritageName;
this.mHeritageAddress = heritageAddress;
}
public int getmImageResourceId() {
return mImageResourceId;
}
public String getmHeritageName() {
return mHeritageName;
}
public String getmHeritageAddress() {
return mHeritageAddress;
}
}
ListView XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="100dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvHeritage">
</ListView>
</RelativeLayout>
List Row XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_margin="10dp">
<ImageView
android:id="#+id/ivHeritage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="33.33"
android:padding="2dp"
android:text="Ngatapol"
android:layout_marginTop="7dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:id="#+id/llHeritageInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="66.66"
android:padding="8dp" >
<TextView
android:id="#+id/tvHeritageName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"
android:text="Ngatapol"
android:textAppearance="?android:textAppearanceMedium"
android:padding="2dp"/>
<TextView
android:id="#+id/tvHeritageAddress"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:text="Taumadi"
android:padding="2dp"/>
</LinearLayout>
</LinearLayout>
listview shows the first item only is because you have set height in heritages_row layout to match_parent which will cover the whole screen height and for the next item, you've to scroll down even if the content of the first item is not covering the whole height.
To make each row to only cover the content its displaying, use wrap_content instead of match_parent.
I have following code that should:
listView = (ListView) findViewById(R.id.listview_github_entries);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
This is what I load into the ListView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="horizontal"
android:clickable="true">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#mipmap/github_icon"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/github_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/github_url"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Here is the Adapter :
public class GithubEntryAdapter extends ArrayAdapter<GithubEntry>{
public GithubEntryAdapter(Activity context, ArrayList<GithubEntry> githubEntries){
super(context, 0, githubEntries);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if (listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
GithubEntry currentGithubEntry = getItem(position);
TextView github_url = (TextView) listItemView.findViewById(R.id.github_url);
github_url.setText(currentGithubEntry.getGithub_url());
TextView github_name = (TextView) listItemView.findViewById(R.id.github_name);
github_name.setText(currentGithubEntry.getGithub_name());
return listItemView;
}
}
This is not working for me. Im no quit sure where I should place this code. Can I place this in the onCreate? If not where should I move it? I completly new in Android and I have also not much experience in Java.
Here is what i did for you..
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview_github_entries);
listView.setAdapter(new GithubEntryAdapter(MainActivity.this, getList()));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView github_url_tv = view.findViewById(R.id.github_url);
String url_text= github_url_tv.getText().toString();
Toast.makeText(MainActivity.this, url_text", Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<GithubEntry> getList() {
ArrayList<GithubEntry> githubEntries = new ArrayList<>();
GithubEntry githubEntry = new GithubEntry();
githubEntry.setGithub_name("Name");
githubEntry.setGithub_url("url");
GithubEntry githubEntry1 = new GithubEntry();
githubEntry1.setGithub_name("Name");
githubEntry1.setGithub_url("url");
GithubEntry githubEntry2 = new GithubEntry();
githubEntry2.setGithub_name("Name");
githubEntry2.setGithub_url("url");
githubEntries.add(githubEntry);
githubEntries.add(githubEntry1);
githubEntries.add(githubEntry2);
return githubEntries;
}
}
Here is adapter
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class GithubEntryAdapter extends ArrayAdapter<GithubEntry> {
public GithubEntryAdapter(Activity context, ArrayList<GithubEntry>
githubEntries){
super(context, 0, githubEntries);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if (listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
GithubEntry currentGithubEntry = getItem(position);
TextView github_url = (TextView) listItemView.findViewById(R.id.github_url);
github_url.setText(currentGithubEntry.getGithub_url());
TextView github_name = (TextView) listItemView.findViewById(R.id.github_name);
github_name.setText(currentGithubEntry.getGithub_name());
return listItemView;
}
}
here is POJO(plan java object) class
class GithubEntry {
private String Github_url;
private String Github_name;
public String getGithub_url() {
return Github_url;
}
public void setGithub_url(String github_url) {
Github_url = github_url;
}
public String getGithub_name() {
return Github_name;
}
public void setGithub_name(String github_name) {
Github_name = github_name;
}
}
and here is list_item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="horizontal"
android:clickable="false">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher_round"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/github_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/github_url"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
and here is activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kaimeramedia.githubentry.MainActivity">
<ListView
android:id="#+id/listview_github_entries"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
If mean that the OnItemClickListeneter not working, then you need to implement a custom adapter by extending ArrayAdater to serve you custom row, And in the custom adapter you can use a callback interface or implement a listener on the view it self See the example.
I think you want to display the list of values here. You should write it inside onCreate because onCreate is a method where you method starts and run. So, Put it inside onCreate. For more correct answer please explain everything.
I'm fairly new to Android programming and tried everything I could I found on SO, but it still doesn't work.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:fillViewport="true"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.northcityproductions.androidiosapptransfertest1.MainActivity">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:id="#+id/imageView1"
android:layout_gravity="center_vertical"
android:clickable="false"
android:padding="5dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:paddingStart="50dip"
android:textSize="20dip"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:clickable="false"
android:layout_alignParentStart="true">
</TextView>
</RelativeLayout>
AndroidListAdapter.java
package com.northcityproductions.androidiosapptransfertest1;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AndroidListAdapter extends ArrayAdapter {
List<String> androidListViewStrings = new ArrayList<String>();
List<Drawable> imagesId = new ArrayList<Drawable>();
Context context;
public AndroidListAdapter(Activity context, List<Drawable> imagesId, List<String> textListView) {
super(context, R.layout.activity_main, textListView);
this.androidListViewStrings = textListView;
this.imagesId = imagesId;
this.context = context;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewRow = layoutInflater.inflate(R.layout.activity_main, null,
true);
TextView mtextView = (TextView) viewRow.findViewById(R.id.textView1);
ImageView mimageView = (ImageView) viewRow.findViewById(R.id.imageView1);
mtextView.setText(androidListViewStrings.get(i));
mimageView.setImageDrawable(imagesId.get(i));
return viewRow;
}
}
Finally, MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get list of apps
int flags = PackageManager.GET_META_DATA |
PackageManager.GET_SHARED_LIBRARY_FILES |
PackageManager.GET_UNINSTALLED_PACKAGES;
PackageManager pm = getPackageManager();
List<ApplicationInfo> applications = pm.getInstalledApplications(flags);
List<String> applicationsInstalled = new ArrayList<String>();
List<Drawable> applicationIcons = new ArrayList<Drawable>();
//Create map and sort alphabetically
Map applicationsList = new HashMap();
for (ApplicationInfo appInfo : applications) {
if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
// System application
} else {
// Installed by user
String appName = (String) pm.getApplicationLabel((appInfo));
appName = appName.substring(0, 1).toUpperCase() + appName.substring(1);
applicationsList.put(appName, pm.getApplicationIcon(appInfo));
}
}
Map<String, Drawable> treeApps = new TreeMap<String, Drawable>(applicationsList);
for (Map.Entry<String, Drawable> appMap : treeApps.entrySet()) {
applicationsInstalled.add(appMap.getKey());
applicationIcons.add(appMap.getValue());
}
//Arrange them in listview
final AndroidListAdapter androidListAdapter = new AndroidListAdapter(this, applicationIcons, applicationsInstalled);
ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(androidListAdapter);
lv1.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("List");
adb.setMessage(" selected Item is="+parent.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
}
I have tried adding the blocksDescendants code in my activity_main.xml under Listview, and Relativelayout, but that doesn't seem to fix it. I also tried setting the focusable property to false for the imageview and textview but that didn't fix it either.
I need to show text below every image in grid view. I have been able to put the images in grid view but how to put text below it? Below I'm posting the code snippets.
fragment_facility_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
FacilityAdapter.class
package com.androidbelieve.HIT_APP;
/**
* Created by Akash on 2/13/2016.
*/
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class FacilityAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.bank, R.drawable.bus,
R.drawable.girlshostel , R.drawable.guesthouse,
R.drawable.gym , R.drawable.library,R.drawable.sports
};
public String[] mThumbNames = {
"Bank", "Bus Service","Guest House", "GYM","Fac1","Fac2"
};
// Constructor
public FacilityAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View gridView;
gridView = new View(mContext);
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
return imageView;
}
}
Thank You
I would rather suggest that instead of creating ImageView dynamically at run time and return that from your getView() method, you should create an xml for your each of the list items. Below is the sample xml with ImageView and TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"/>
</LinearLayout>
Also you should follow ViewHolder Patternto make your GridView memory efficient. Your getView() method will look alike this
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.yourxml,
null);
holder.textview= (TextView) convertView.findViewById(R.id.text);
holder.imageview= (ImageView) convertView.findViewById(R.id.image);
holder.imageView.getLayoutParams().width = yourImageWidth;
holder.imageView.getLayoutParams().height = yourImageHeight;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setImageResource(mThumbIds[position]);
holder.textview.setText(mThumbNames[position]);
return convertView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
}
Try to extend this:
SimpleAdapter
or use it by default like:
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.bank, R.drawable.bus,
R.drawable.girlshostel , R.drawable.guesthouse,
R.drawable.gym , R.drawable.library,R.drawable.sports
};
public String[] mThumbNames = {"Bank", "Bus Service","Guest House", "GYM","Fac1","Fac2"};
Simple adapter= new SimpleAdapter(mContext, List<?> your_list, R.layout.your_layout_file, from, to);
You also have to make a layout file and define how the image and text you would like to look for each gridview item like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/this_image_id_have_to_be_used_in_your_to_array"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/this_text_id_have_to_be_used_in_your_to_array"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"/>
</LinearLayout>
Hope it helps!!!
So i want to make my CustomArrayAdapter class generic.
CustomDialogFragmentNotGeneric:
public class CustomDialogFragment extends DialogFragment
{
TextView listViewItemTextView;
ArrayAdapter<String> arrayAdapter;
ListView dialogListView;
String[] items = {"Hello","Hello there","Hi","Hi there"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.dialog, container,false);
getDialog().setTitle("Choose an option"); // Set dialog title
listViewItemTextView = (TextView) rootView.findViewById(R.id.list_view_item_text_view_id);
dialogListView = (ListView) rootView.findViewById(R.id.dialog_list_view_id);
getDialog().setTitle("Opening Words"); // Setting dialog title
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(getActivity(), items);
dialogListView.setAdapter(customArrayAdapter);
dialogListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
Toast.makeText(getActivity(), items[position], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
It's not generic because of the String[] itemm = line.
So instead of building a lot of classes that in each there will be a different String[] item, how do i make that generic?
dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/dialog_list_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
MyCustomArrayAdapter class:
package com.example.predesignedmails;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomArrayAdapter extends ArrayAdapter<String>
{
Context context;
String[] items;
LayoutInflater layoutInflater;
public CustomArrayAdapter(Context context, String[] items)
{
super(context, R.layout.list_view_row,items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
this.layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = this.layoutInflater.inflate(R.layout.list_view_row,parent,false);
}
TextView rowTextView = (TextView) convertView.findViewById(R.id.row_text_view_id);
rowTextView.setText(this.items[position]);
return convertView;
}
}
list_view_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/row_text_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
I have put a lot of effort into this post. Please help me guys. Thanks.
EDIT
my activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.predesignedmails.LoveMailsActivity" >
<TextView
android:id="#+id/love_email_emai_to_send_to_text_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/emai_to_send_to_text_view_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#color/opening_words_list_view_header_color"
/>
<EditText
android:id="#+id/love_email_email_to_send_to_edit_text_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/emai_to_send_to_edit_text_hint"
android:inputType="textEmailAddress"
android:textSize="18sp"
android:textColor="#color/selection_text_color"
android:layout_below="#id/love_email_emai_to_send_to_text_view_id"
/>
<TextView
android:id="#+id/love_email_opening_words_header_text_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/love_email_opening_words_text_view_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#color/opening_words_list_view_header_color"
android:layout_below="#id/love_email_email_to_send_to_edit_text_id"
/>
<TextView
android:id="#+id/love_email_opening_words_text_view_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/initial_text"
android:textSize="18sp"
android:textColor="#color/selection_text_color"
android:layout_below="#id/love_email_opening_words_header_text_view_id"
/>
</RelativeLayout>
ArrayAdapter is already generic. Based on your current code, you can get rid of your entire CustomArrayAdapter class and simply use this constructor (replacing String with whatever type your items are):
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
R.layout.list_view_row, R.id.row_text_view_id, items);
If you plan to keep CustomArrayAdapter, you can declare it like this to keep the generics:
public class CustomArrayAdapter<T> extends ArrayAdapter<T> {
...
}
Naturally you would use T instead of String wherever necessary.