Get data from ListView when clicking ListView's child

独自空忆成欢 提交于 2019-12-06 20:51:28

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 
     }
});

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