简体   繁体   中英

How to set textView in custom row view of listView

i'm trying to set textView in custom row view of listView like below but the app crashes returning null pointer exception

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

but when i put it under setOnClickListener it works

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

You should be doing this inside your ListView's adapter. Whatever data you are using the back your adapter should contain the text you want so that you can set it on the appropriate TextView when you actually create the row view in getView() .

It's important to note that getChildAt(index) returns the child at the given index from the ListView's current children . In other words, getChildAt(0) does not necessarily give you the list item at position 0. The user may have scrolled the list so that it now shows data from positions 10 through 15 (for example), in which case getChildAt(0) gives you the view for position 10, not position 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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