检索Listview行数据(包含两个TextView)

时间:2012-06-16 12:24:55

标签: android android-layout android-listview classcastexception onclicklistener

我有ListView。每行ListView包含2 TextView

我为setOnItemClickListener实施了ListView如下:

list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

            // String item = list.getItemAtPosition(position).toString();
            TextView item =(TextView)list.getItemAtPosition(position);
        }});

但是它给了我'ClassCastException',如下所示:

java.lang.ClassCastException: java.lang.Integer
at com.idealake.lic.Activities.PlansActivity$1.onItemClick(PlansActivity.java:62)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3513)

我的怀疑是:

  • 如何检索TextView行中ListView的内容。
  • 如何在检索数据时区分1st TextView和2nd TextView

任何帮助表示感谢。

4 个答案:

答案 0 :(得分:3)

使用 findViewbyId()

而不是,

   TextView item =(TextView)list.getItemAtPosition(position);

试试这个,

   TextView item =(TextView)list.findViewbyId(R.id.textviewID);

如果您发现这不起作用,那么只需尝试使用您的视图对象,

  TextView item =(TextView)view.findViewbyId(R.id.textviewID);

在ItemCLick Listener上的Bcoz,您将获得您尝试引用的视图中的确切元素。因此,您无需再次使用位置来查找TextView。

答案 1 :(得分:2)

setTag(id, value)getView() getTag(id)可以onItemClick()

public View getView(int position, View convertView, ViewGroup parent) {

    convertView = getLayoutInflater().inflate(R.layout.xxx, null);
    TextView mTextView1 = (TextView) convertView .findViewById(R.id.txt1);
    TextView mTextView2 = (TextView) convertView .findViewById(R.id.txt2);

    convertView.setTag(R.id.txt1, mTextView1);
    convertView.setTag(R.id.txt2, mTextView2);
    return convertView;
}

在你的List的Click监听器中你喜欢这个

list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        TextView mTextView1 =(TextView)view.getTag(R.id.txt1);
        TextView mTextView2 =(TextView)view.getTag(R.id.txt2);
    }});

答案 2 :(得分:2)

优化方式是::

TextView textview1 =(TextView)view.findViewById(R.id.textview1);
                              ^^^^
TextView textview2 =(TextView)view.findViewById(R.id.textview2);

答案 3 :(得分:1)

list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

            TextView item =(TextView)view.findViewById(R.id.textview1);
            TextView item =(TextView)view.findViewById(R.id.textview2);

        }});