单击ListView子级时从ListView获取数据

时间:2013-04-28 05:34:10

标签: android android-layout android-listview

我有一个ListView,每行一个按钮。如果我需要在单击行时获取数据,那么在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
        }
    });

实际上,我需要在单击ListView的行的按钮时获取数据(即:CustomType对象),而不是行本身。因为OnClickListener没有类似AdapterView的东西 参数(很明显),我想知道如何处理这个? 到目前为止,它让我得到按钮的父母,这是列表视图,并以某种方式进入行的位置点击按钮,然后 打电话给: myAdapter.getItem(位置); 但这只是一个想法,所以,请在这里感谢一些帮助。

先谢谢。

2 个答案:

答案 0 :(得分:4)

您可能正在为ListView使用自定义适配器,因此最简单的方法是在适配器的getView()方法中设置position参数作为Button的标记。然后,您可以在OnClickListener中检索标记,然后您就会知道单击了哪一行:

@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();
         }
    });
    //...
}

您还可以从行视图中提取数据。如果可以在该行的视图中找到该行的所有数据,则此方法将起作用:

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

答案 1 :(得分:0)

在适配器中添加一个返回CustomType对象

的自定义方法
    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);
     }
    });