3

我有以下带有自定义列表项的 ListView:

custom_list_item

我想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敬酒ToggleButton。尝试使用此代码获取Text1or值时: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从最后ListView一项中获得价值。

有任何想法吗?

4

2 回答 2

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

您可以使用上面的代码获得任何值..

于 2012-06-25T11:54:52.917 回答
1

使用按钮的 setTag 和 GetTag

tb_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();
                }
            });
于 2012-06-25T11:47:10.970 回答