使用按钮从ListView内的EditText获取文本会返回错误的值

时间:2016-03-14 07:36:13

标签: android listview

我有一个带有Custom BaseAdapter的ListView。 ListView的每一行都有一个EditText和一个Button。我想在单击按钮时获取EditText值,但是,在我单击按钮后,应用程序将返回另一行的值。这是我的getView方法:

public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v1 = convertView;
        if (v1 == null)
        {
            LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v1 = vi.inflate(R.layout.annotation_item2, null);
            customHolder = new CustomHolder();
            customHolder.edtTotal = (EditText) v1.findViewById(R.id.edtTotal);
            customHolder.btnOk = (Button) v1.findViewById(R.id.btnOk);

            v1.setTag(customHolder);
        } else {
            customHolder = (CustomHolder) v1.getTag();
        }

        customHolder.btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("Value", customHolder.edtTotal.getText().toString());
           }
        });

        return v1;
}

2 个答案:

答案 0 :(得分:1)

试试这个可能会有所帮助

  btnOk.setTag(customHolder.edtTotal);
     customHolder.btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.v("Value",((EditText)v.getTag()).getText().toString());
           }
        });

答案 1 :(得分:0)

您应该尝试使用onItemClick。这是一些代码:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    EditText txtInfo = (EditText) view.findViewById(R.id.your_edittext_id);
    Button btnTest = (Button) view.findViewById(R.id.your_button_id);
    final String text = txtInfo.getText().toString();
    //do sth to show your values.
    btnTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Log.v("Value", text);
        }
    });
}

不要忘记在课堂上实施AdapterView.OnItemClickListener。上面的代码在您自己的类中运行,而不是在adapter

中运行