繁体   English   中英

如何在listView的自定义行视图中设置textView

[英]How to set textView in custom row view of listView

我试图在listView的自定义行视图中设置textView,如下所示,但应用程序崩溃并返回空指针异常

TextView txtrow = (TextView) getListView().getChildAt(i).findViewById(R.id.text11);
txtrow.setText("text");

但是当我将其放在setOnClickListener下时,它可以工作

button.setOnClickListener(new View.OnClickListener() {      
        @Override
        public void onClick(View v) {
            TextView txtrow = (TextView) getListView().getChildAt(i).findViewById(R.id.text11);
            txtrow.setText("text");
        }
    });

您应该在ListView的适配器中执行此操作。 无论适配器背面使用的是什么数据,都应包含所需的文本,以便在getView()实际创建行视图时可以在适当的TextView上进行设置。

重要的是要注意, getChildAt(index) 从ListView的当前children返回给定索引处的孩子 换句话说, getChildAt(0) 不一定给你列表项目位置0的用户可能已经滚动该列表,以便它现在示出了通过从15位的10个数据(例如),在这种情况下getChildAt(0)为您提供位置10而非位置0的视图。

To set text in custom row in listview 
Please follow the following points 
1. custom arrayadapter by extending Arrayadpater (for simple)
2. and overwrite getview as following

 @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    textView.setText(values[position]);
    return rowView;
  }

3. and set the adapter to the listview 
And for more detial please refer this site
[http://www.vogella.com/tutorials/AndroidListView/article.html][1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM