2013-04-28 52 views
1

我有一个ListView,每行一个按钮。如果我需要得到的数据行被点击的时候,那么这将是很容易做到的onItemClickListener内的以下内容:单击ListView的子项时从ListView获取数据

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

其实,事情是,我需要得到的数据(即:CustomType对象)当ListView的行get按钮被点击时,而不是行本身。由于OnClickListener没有像AdapterView这样的参数(显然是),我想知道我该如何处理这个? 到目前为止,它发生在我得到按钮的父母,这是列表视图,并以某种方式进入最左边的位置点击按钮,然后 调用类似于: myAdapter.getItem(position); 但是只是一个想法,所以请,我会很感激这里的一些帮助。

在此先感谢。

回答

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

我需要做类似的东西里面按钮的单击事件监听器和ListView不onItemClick监听器 – Daniel 2013-04-28 07:50:04

相关问题