I'm attempting to set and onClick listener on the items in my listView however for some reason the toast never appears when they are clicked. I'm not sure exactly what is happening in this instance but any suggestions are greatly appreciated.
source:
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView
.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView
.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getVideoName());
holder.txtCmd.setText(cmd.getCmd());
// holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoURL() + "");
holder.imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, "Clicked on image", Toast.LENGTH_LONG)
.show();
}
});
return convertView;
}
}
Make your ImageView clickable and focusable
Your use of the ViewHolder pattern could be improved in a couple of places. For one, you keep resetting your onClickListener() every time getView is called. You should make the following changes:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView == null){
view = context.getLayoutInflater().inflate(R.layout.list_item2, null);
final ViewHolder holder = new ViewHolder();
holder.txtSuccess = (TextView) view
.findViewById(R.id.success);
holder.txtCmd = (TextView) view.findViewById(R.id.cmd);
holder.txtPrice = (TextView) view.findViewById(R.id.price);
holder.imageView = (ImageView) view.findViewById(R.id.thumbnail);
holder.imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, "Clicked on image", Toast.LENGTH_LONG)
.show();
}
});
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getVideoName());
holder.txtCmd.setText(cmd.getCmd());
// holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoURL() + "");
return view;
}
Also, you should make your ViewHolder inner class static.
/* private view holder class */
private static class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
Try to implement touch instead of click or using ImageButton instead of ImageView
holder.imageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
Toast.makeText(context, "Clicked on image", Toast.LENGTH_LONG)
.show();
break;
}
}
return true;
}
});
Related
I have a custom listview with a button to add more elements
but when I add and element the app crash, but when I restart I find that the element is added, (rarely it doesn't crash)
And i
I use custom adapter
class CustomAdapter extends BaseAdapter {
ArrayList<ListItem> listItems = new ArrayList<ListItem>();
CustomAdapter(ArrayList<ListItem> list){
this.listItems = list;
}
#Override
public int getCount() {
return listItems.size();
}
#Override
public Object getItem(int position) {
return listItems.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.list_item,null);
TextView name = (TextView) view.findViewById(R.id.name);
TextView lastm = (TextView) view.findViewById(R.id.last);
TextView time = (TextView) view.findViewById(R.id.time);
CircleImageView pic= (CircleImageView) view.findViewById(R.id.pic);
name.setText(listItems.get(i).name);
lastm.setText(listItems.get(i).lastm);
time.setText(listItems.get(i).time);
Bitmap bmp = BitmapFactory.decodeByteArray(listItems.get(i).pic,0,listItems.get(i).pic.length);
pic.setImageBitmap(bmp);
return view;
}
}
and when I add an element the app crashs
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText=(EditText) mView.findViewById(R.id.name);
String name=editText.getText().toString();
boolean result=myDataBase.insertData(imageViewToByte(img),name,"no messages yet","");
if (result) {
Toast.makeText(Main2Activity.this, "Saved in DATABASE", Toast.LENGTH_SHORT).show();
viewLastData();
dialog.dismiss();
}
If your ListView lags it's because you used wrap_content for the listView's layout_height. It forces your ListView to count all the items inside and it has a huge performance impact.
So replace wrap_content by match_parent to avoid those lags.
EDIT: Use a ViewHolder pattern too in your Adapter, see this link.
Here is an example:
// ViewHolder Pattern
private static class ViewHolder {
TextView name, status;
}
#Override #NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater vi = LayoutInflater.from(getContext());
convertView = vi.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text_name);
holder.status = (TextView) convertView.findViewById(R.id.another_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Then do the other stuff with your item
// to populate your listView
// ...
return convertView
}
I wanted to show the image only at the selected row from listview. Here is the code:
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
return attendeeList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.attendee_listview_row,
null);
viewHolder = new ViewHolder();
viewHolder.txt_dName = (TextView) convertView
.findViewById(R.id.txtDisplayName);
viewHolder.txt_dAddr = (TextView) convertView
.findViewById(R.id.txtDisplayAddr);
viewHolder.txt_dtelNo = (TextView) convertView
.findViewById(R.id.txtDisplayTelNo);
viewHolder.btn_scan = (ImageView) convertView.findViewById(R.id.btnScan);
viewHolder.registered_tag = (ImageView) convertView.findViewById(R.id.ivRegisteredTag);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_dName.setText(attendeeList.get(position)
.getAccountName().trim());
viewHolder.txt_dAddr.setText(attendeeList.get(position)
.getAttendeeAddr().trim());
viewHolder.txt_dtelNo.setText("Tel no: "
+ attendeeList.get(position).getTelNo().trim());
viewHolder.btn_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
viewHolder.registered_tag.setVisibility(View.VISIBLE);
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
return convertView;
}
}
With these code, I am trying to show the registered_tag upon btn_scan onClick. However, the image is not really showing at the selected row. It shows at other row instead.
Any ideas? Thanks in advance.
Probably you are getting last row image change when clicking on any row because viewHolder will contain last row view when getView called. Use setTag and getTag method of viewHolder.btn_scan view to save and get selected row view in onClick method:
viewHolder.btn_scan.setTag(viewHolder);
viewHolder.btn_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
ViewHolder selectedViewHolder=(ViewHolder)v.getTag();
selectedViewHolder.registered_tag.setVisibility(View.VISIBLE);
...
}
});
I'm trying to do a custom listview with a favorite option, the thing is that when I add some items to favorite and then scroll down the fav button change order randomly, the other thing that I need help with is that I don't know how to change a favorite imageview when other is clicked (Because You can only have 1 favorite option)
This is my custom adapter
public class LineasAdapter extends BaseAdapter {
Context context;
protected List<Lineas> lineas;
LayoutInflater inflater;
public LineasAdapter(Context context, List<Lineas> lista){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.lineas = lista;
}
#Override
public int getCount() {
return lineas.size();
}
#Override
public Object getItem(int position) {
return lineas.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.item_lista,
parent, false);
holder.numero = (TextView) convertView
.findViewById(R.id.number);
holder.titulo = (TextView) convertView
.findViewById(R.id.titulo);
holder.subtitulo = (TextView) convertView
.findViewById(R.id.subtitulo);
holder.star = (ImageView) convertView
.findViewById(R.id.star);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Lineas linea = lineas.get(position);
holder.numero.setText(linea.numero_s());
holder.titulo.setText(linea.titulo());
holder.subtitulo.setText(linea.subtitulo());
final SharedPreferences.Editor editor = convertView.getContext().getSharedPreferences("Favorito",0).edit();
final int numero = linea.numero();
final Context c = convertView.getContext();
final ImageView estrella = holder.star;
/** this is where I change my fav button and add the number to some sharedpreferences **/
holder.star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("linea", numero );
editor.commit();
Toast.makeText(c,"Has agregado a favoritos a el cole numero "+String.valueOf(numero), Toast.LENGTH_SHORT ).show();
estrella.setImageResource(R.drawable.star);
}
});
return convertView;
}
private class ViewHolder {
TextView numero;
TextView titulo;
TextView subtitulo;
ImageView star;
}
}
replace getview method with follwing ...
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.item_lista,parent, false);
holder.numero = (TextView) convertView.findViewById(R.id.number);
holder.titulo = (TextView) convertView.findViewById(R.id.titulo);
holder.subtitulo = (TextView) convertView.findViewById(R.id.subtitulo);
holder.star = (ImageView) convertView.findViewById(R.id.star);
convertView.setTag(holder);
Lineas linea = lineas.get(position);
holder.numero.setText(linea.numero_s());
holder.titulo.setText(linea.titulo());
holder.subtitulo.setText(linea.subtitulo());
final SharedPreferences.Editor editor = convertView.getContext().getSharedPreferences("Favorito",0).edit();
final int numero = linea.numero();
final Context c = convertView.getContext();
final ImageView estrella = holder.star;
/** this is where I change my fav button and add the number to some sharedpreferences **/
holder.star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("linea", numero );
editor.commit();
Toast.makeText(c,"Has agregado a favoritos a el cole numero "+String.valueOf(numero), Toast.LENGTH_SHORT ).show();
estrella.setImageResource(R.drawable.star);
}
});
return convertView;
}
The int "pos" is not passing correctly.
How I can the to correct value when the ImageView is OnClick().
It seems when the listener activate the information is not accurate anymore.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vHolder;
if (convertView != null)
vHolder = (ViewHolder) convertView.getTag();
else {
convertView = mInflater.inflate(R.layout.car_list, null);
vHolder = new ViewHolder();
vHolder.textView = ((TextView) convertView.findViewById(R.id.tvCarListText));
vHolder.textView2 = ((TextView) convertView.findViewById(R.id.tvCarDescriptionListText));
vHolder.imageView = ((ImageView) convertView.findViewById(R.id.ivCarListMenuIcon));
vHolder.relativeLayout = ((RelativeLayout) convertView.findViewById(R.id.relativeLayout));
convertView.setTag(vHolder);
CarItem c = mItems.get(position);
final int pos = (int)c.getCarID();
vHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCarEditDialog(pos); //THIS IS PASSING WRONG <--------------
}
});
}
return convertView;
}
Use ImageView.setTag() to get position of clicked row on ImageVIew click as:
vHolder.imageView.setTag(pos); // set current pos
vHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCarEditDialog(Integer.parseInt(v.getTag().toString()));
}
});
you can easily do it like this :
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder vHolder;
if (convertView != null)
vHolder = (ViewHolder) convertView.getTag();
else {
convertView = mInflater.inflate(R.layout.car_list, null);
vHolder = new ViewHolder();
vHolder.textView = ((TextView) convertView.findViewById(R.id.tvCarListText));
vHolder.textView2 = ((TextView) convertView.findViewById(R.id.tvCarDescriptionListText));
vHolder.imageView = ((ImageView) convertView.findViewById(R.id.ivCarListMenuIcon));
vHolder.relativeLayout = ((RelativeLayout) convertView.findViewById(R.id.relativeLayout));
convertView.setTag(vHolder);
}
vHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCarEditDialog((int)((CarItem)mItems.get(position)).getCarId);
}
});
return convertView;
}
Is it possible to get an item view based on its position in the adapter and not in the visible views in the ListView?
I am aware of functions like getChildAt() and getItemIdAtPosition() however they provide information based on the visible views inside ListView. I am also aware that Android recycles views which means that I can only work with the visible views in the ListView.
My objective is to have a universal identifier for each item since I am using CursorAdapter so I don't have to calculate the item's position relative to the visible items.
Here's how I accomplished this. Within my (custom) adapter class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(textViewResourceId, parent, false);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.name = (TextView) view.findViewById(R.id.name);
viewHolder.button = (ImageButton) view.findViewById(R.id.button);
viewHolder.button.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = (int) viewHolder.button.getTag();
Log.d(TAG, "Position is: " +position);
}
});
view.setTag(viewHolder);
viewHolder.button.setTag(items.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).button.setTag(items.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
return view;
}
Essentially the trick is to set and retrieve the position index via the setTag and getTag methods. The items variable refers to the ArrayList containing my custom (adapter) objects.
Also see this tutorial for in-depth examples. Let me know if you need me to clarify anything.
See below code:
public static class ViewHolder
{
public TextView nm;
public TextView tnm;
public TextView tr;
public TextView re;
public TextView membercount;
public TextView membernm;
public TextView email;
public TextView phone;
public ImageView ii;
}
class ImageAdapter extends ArrayAdapter<CoordinatorData>
{
private ArrayList<CoordinatorData> items;
public FoodDriveImageLoader imageLoader;
public ImageAdapter(Context context, int textViewResourceId,ArrayList<CoordinatorData> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
ViewHolder holder = null;
if (v == null)
{
try
{
holder=new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new FoodDriveImageLoader(FoodDriveModule.this);
v = vi.inflate(R.layout.virtual_food_drive_row, null);
//System.out.println("layout is null.......");
holder.nm = (TextView) v.findViewById(R.id.name);
holder.tnm = (TextView) v.findViewById(R.id.teamname);
holder.tr = (TextView) v.findViewById(R.id.target);
holder.re = (TextView) v.findViewById(R.id.received);
holder.membercount = new TextView(FoodDriveModule.this);
holder.membernm = new TextView(FoodDriveModule.this);
holder.email = new TextView(FoodDriveModule.this);
holder.phone = new TextView(FoodDriveModule.this);
holder.ii = (ImageView) v.findViewById(R.id.icon);
v.setTag(holder);
}
catch(Exception e)
{
System.out.println("Excption Caught"+e);
}
}
else
{
holder=(ViewHolder)v.getTag();
}
CoordinatorData co = items.get(position);
holder.nm.setText(co.getName());
holder.tnm.setText(co.getTeamName());
holder.tr.setText(co.getTarget());
holder.re.setText(co.getReceived());
holder.ii.setTag(co.getImage());
imageLoader.DisplayImage(co.getImage(), FoodDriveModule.this , holder.ii);
if (co != null)
{
}
return v;
}
}
A better option is to identify using the data returned by the CursorAdapter rather than visible views.
For example if your data is in a Array , each data item has a unique index.
Here, Its very short described code, you can simple re-use viewholder pattern to increase listview performance
Write below code in your getview() method
ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.skateparklist, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView
.findViewById(R.id.textView1);
holder.DistanceView = (TextView) convertView
.findViewById(R.id.textView2);
holder.imgview = (NetworkImageView) convertView
.findViewById(R.id.imgSkatepark);
convertView.setTag(holder); //PLEASE PASS HOLDER AS OBJECT PARAM , CAUSE YOU CAN NOY PASS POSITION IT WILL BE CONFLICT Holder and Integer can not cast
//BECAUSE WE NEED TO REUSE CREATED HOLDER
} else {
holder = (ViewHolder) convertView.getTag();
}
// your controls/UI setup
holder.DistanceView.setText(strDistance);
......
return convertview
Listview lv = (ListView) findViewById(R.id.previewlist);
final BaseAdapter adapter = new PreviewAdapter(this, name, age);
confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = null;
String value;
for (int i = 0; i < adapter.getCount(); i++) {
view = adapter.getView(i, view, lv);
Textview et = (TextView) view.findViewById(R.id.passfare);
value=et.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
}
});