我有以下带有自定义列表项的ListView:
我想从单击TextView
的列表项中获取ToggleButton
值。
这是构建列表的适配器:
public class simpleAdapter extends SimpleAdapter {
public simpleAdapter(Context context,
ArrayList<HashMap<String, String>> list, int resource,
String[] from, int[] to) {
super(context, list, resource, from, to);
// TODO Auto-generated constructor stub
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// return super.getView(position, convertView, parent);
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.user_campaigns_list_item, parent, false);
tb_campaigns_list_toggle = (ToggleButton) convertView
.findViewById(R.id.tb_campaigns_list_toggle);
tb_campaigns_list_toggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
return super.getView(position, convertView, parent);
}
}
使用此代码,我可以祝贺position
点击list item
的{{1}}。
尝试使用此代码获取ToggleButton
或Text1
值时:
id1
我总是从上一个TextView Text1 = (TextView)convertView.findViewById(R.id.Text1_id); //this line is outside the onClick(View v) method
String Text1_value = Text1.getText().toString();
Toast.makeText(getApplicationContext(), Text1_value, Toast.LENGTH_SHORT).show();
项中获得Text1
的值。
任何想法?
答案 0 :(得分:8)
在listview的onItemClick函数中,粘贴以下代码:
View parentView = (View) view.getParent();
textview1 = ((TextView) parentView
.findViewById(R.id.textview1)).getText().toString();
textview2 = ((TextView) parentView
.findViewById(R.id.textview2)).getText().toString();
textview3 = ((TextView) parentView
.findViewById(R.id.textview3)).getText().toString();
您可以使用上述代码获取任何值。
答案 1 :(得分:1)
使用按钮
的setTag和GetTagtb_campaigns_list_toggle = (ToggleButton) convertView
.findViewById(R.id.tb_campaigns_list_toggle);
tb_campaigns_list_toggle.setTag(position);//<-------------
tb_campaigns_list_toggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int index = -1;
Object obj = v.getTag();//<-------------
if(obj instanceOf Integer){
index = ((Integer)obj).getIntValue();
}
Toast.makeText(getApplicationContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});