how to get a list item position by clicking the button inside it?

南楼画角 提交于 2019-11-28 09:04:16

Actually, I used the same approach - just added casting the parent layout and I got the position w/o any exception

public void deleteButtonClick(View v) {
        //TODO Remove favorite - DB + file system
        Toast.makeText(this, "Deleting bookmark", Toast.LENGTH_SHORT).show();
        final int position = getListView().getPositionForView((LinearLayout)v.getParent());
        if (position >= 0) {
            Favorite o = (Favorite) this.getListAdapter().getItem(position);
        }
}

My layout for listview row :

<?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/com.bbox.application"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.markupartist.android.widget.ActionBar
        android:id="@+id/actionbar" app:title="@string/ac_title" style="@style/ActionBar" />
    <ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_weight="5"
        android:background="@drawable/categrory_bckgr" />
    <TextView android:id="@+id/android:empty"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:text="@string/main_no_items" />

</LinearLayout>

I hope it'll help.

An easier solution to this probably is when your Activity implements OnClickListener and you set the (casted) Context as OnClickListener to any view you want in the Adapter. For more robust code you can check with instanceof.

public class MyActivity implements OnClickListener {

    // ...

}

public class MyAdapter extends CursorAdapter {

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        final TextView tv = (View) view.findViewById(R.id.text1);

        setOnClickListener((OnClickListener)context);

        tv.setTag(cursor.getPosition());

    }

}

For convenience you can set the items position in the adapter as Tag of the view. That way you can easily lookup the whole item in the adapter.

We can get the position by implementing onClickListener inside the getView method of adapter.

ADAPTER :

public class DetailsListAdapter extends BaseAdapter {
Context context;
ArrayList<Profile> data;

public DetailsListAdapter(Context context, ArrayList<Profile> data) {
    this.context = context;
    this.data = data;
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.list_item_logs_details, null);
        viewHolder = new ViewHolder();
        viewHolder.btn = (Button) convertView.findViewById(R.id.log_details_1_a);
        viewHolder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    Log.d("statusPosition","position "+position);
            }
        });
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

public static class ViewHolder {
    TextView tv2, tv3, tv3a, tv4, tv4a;
    Button btn;
}
}

ListView with Clickable Buttons!!!

Well...., here's the rough method to solve my problem SO FAR....

item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:orientation="horizontal"
            android:layout_height="wrap_content">
<TextView android:id="@+id/showTv"
      android:layout_alignParentLeft="true"
      android:gravity="center_vertical"
      android:textSize="24dip"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content" /> 
 <RelativeLayout android:id="@+id/jjjj"
                 android:layout_alignParentRight="true"
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content">        
      <Button android:id="@+id/gointoBt"
               android:focusable="false"
               android:layout_alignParentRight="true"
               android:text="abc"
               android:layout_height="wrap_content"
               android:layout_width="wrap_content"/> 
      <Button android:id="@+id/chooseBt"
              android:layout_toLeftOf="@id/gointoBt"
              android:layout_marginRight="10dip"
              android:text="text"
              android:focusable="false"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"/>
  </RelativeLayout> 

MySimpleAdapter:

import ........;

public class MySimpleAdapter extends SimpleAdapter {

private final Context context;
private List<Map<String, Object>> data;
private int resource;
private String[] from;
private int[] to;

public MySimpleAdapter(Context context,List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
   super(context, data, resource, from, to);
   this.context=context;
   this.data=(List<Map<String, Object>>) data;
   this.resource=resource;
   this.from=from;
   this.to=to;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

   LayoutInflater inflater = ((Activity)context).getLayoutInflater();
   View rowView = inflater.inflate(resource, null, true); 
   Map<String, Object> medMap=data.get(position);
   final TextView[] showTv=new TextView[from.length]; 

   for (int i = 0; i < from.length; i++) { 
    showTv[i]=(TextView)rowView.findViewById(to[i]);
    showTv[i].setText(""+medMap.get(from[i]));
   }
Button btn=(Button)rowView.findViewById(R.id.gointoBt);
   Button.OnClickListener mOkOnClickListener = new Button.OnClickListener()
      {
         public void onClick(View v) {
         Log.v("ttttttt", ""+showTv[0].getText());
         Toast.makeText(context,""+showTv[0].getText(), Toast.LENGTH_LONG).show();
         }
     };
 btn.setOnClickListener(mOkOnClickListener); 

     Button btn2=(Button)rowView.findViewById(R.id.chooseBt);
   Button.OnClickListener mOkOnClickListener2 = new Button.OnClickListener()
      {
          public void onClick(View v) {
          Log.v("hhhhhhh", ""+showTv[0].getText());
          Toast.makeText(context,"abc"+showTv[0].getText(), Toast.LENGTH_LONG).show();
          }
      };
   btn2.setOnClickListener(mOkOnClickListener2);     
   return rowView; 
}
}

Activty:

import .......;

public class   ActivityMain extends Activity {

ListView listview;
List<Map<String,Object>> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setTitle("My work");
   prepareData(); 
   listview =new ListView(this);
   MySimpleAdapter adapter=new MySimpleAdapter(this,data,R.layout.item,new String[]      {"uu"},new int[]{R.id.showTv});

   listview.setAdapter(adapter);                            
     setContentView(listview);

}
private void prepareData(){
   data=new ArrayList<Map<String,Object>>();
   Map<String,Object> item;
   item=new HashMap<String,Object>();
   item.put("uu", "hello");
   data.add(item);
   item=new HashMap<String,Object>();
   item.put("uu", "myyou");
   data.add(item);
   item=new HashMap<String,Object>();
   item.put("uu", "piero");
   data.add(item);
}

}

Thanks for that Man that is so kind to provide this AWESOME yet Mightiest tutorial.... which anyone here couldn't give to the noobs....

I think one more best approach is there.You can add one tag as position with the button using (button.setTag()) method and whenever user will click button just take the tag of this button. it will more easy.

Thanks and Regards Rahul

Very Simple. In your Adapter class getView method change int position to final int position.

public View getView(final int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(yourcustomizeditemview.xml, parent,
                false);
Button btn= (Button) row.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(context, " "+position, Toast.LENGTH_SHORT).show();

            }
        });
return row;
    }

now on Button click Toast shows the position of item in which Button is present.

It seems in onClick() that mListView is null. It's possible that

auto = (ListView)findViewById(R.id.auto);

returned null, because a view of R.id.auto couldn't be found in the present layout. I'd put a debugger breakpoint just after that line and see.

Enas AL Saeek

do you execute this

btnNxt = (Button) findViewById(R.id.btnNext);
 btnNxt.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View arg0) {
  //Here I need to get that position
});

inside the getView method? if so it's very easy

 btnNxt = (Button) findViewById(R.id.btnNext);
 btnNxt.setTag(position);
 btnNxt.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View arg0) {
  int position=(Integer)arg0.getTag();
});

from this: https://stackoverflow.com/a/20542034

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!