Get data from ListView when clicking ListView's child

ε祈祈猫儿з 提交于 2020-01-03 03:13:13

问题


I have a ListView with one button per row. If I needed to get the data when the row gets clicked, then it would be pretty easy to do the following inside the onItemClickListener:

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            CustomType type = (CustomType) arg0.getItemAtPosition(arg2);        //get data related to position arg2 item
        }
    });

Actually, the thing is that I need to get the data(i.e: CustomType object) when the button of the ListView's row get's clicked, and not the row itself. Since OnClickListener doesn't have something like AdapterView as a parameter(obviously), I would like to know how can I handle this?. So far, It ocurred to me getting the button's parent, wich is the listview, and somehow getting in wich row's position the clicked button is, and then call something like: myAdapter.getItem(position); but is just an idea, so please, I'll appreciate some help over here.

Thanks in Advance.


回答1:


You're probably using a custom adapter for your ListView so the easiest way to do what you want is to set in the getView() method of the adapter the position parameter as the tag for the Button. You could then retrieve the tag in the OnClickListener and you'll know then which row was clicked:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //...
    button.setTag(Integer.valueOf(position));
    button.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v) {
              Integer rowPosition = (Integer)v.getTag();
         }
    });
    //...
}

You could also extract the data from the row views. This will work if all the data for the row can be found in the view from that row:

button.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
          LinearLayout row = (LinearLayout)v.getParent(); I assumed your row root is a LinearLayout
         // now look for the row views in the row and extract the data from each one to
         // build the entire row's data 
     }
});



回答2:


Add one custom method in Adapter that return CustomType object

    public CustomType  getObjectDetails(int clickedPosition){
        CustomType  customType = this.list.get(clickedPosition);
        return customType ;
    }


 public void onItemClick(AdapterView<?> arg0, View arg1, int Position,long arg3) {
          CustomType type = getObjectDetails(Position);
     }
    });


来源:https://stackoverflow.com/questions/16259960/get-data-from-listview-when-clicking-listviews-child

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