问题
I need to dynamically change the background color of a child view of a ListView
at a specific index. So I need to get the view first before applying the background.
I have tried the following.
getViewAt(int index)
- this is not applicable to ListView
.
getChildAt(int index)
- this gives runtime NPE error
A Google search returns irrelevant results.
Please help me out. Thank you.
回答1:
I figured out how to do this.
I really think that one should not have to post code and logcat for a question that is similar to "How to set background image".
Anyway my answer is, in short, set position as tag for every child in the listview through your adapter's getView() and then get any child using findViewWithTag(Object tag).
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = (LinearLayout)inflater.inflate(R.layout.some_layout, parent, false); .
convertView.setTag(String.valueOf(position));
}
And whenever you need to get a specific child.
View v = mylistview.findViewWithTag(String.valueOf(index));
To change background color.
v.setBackgroundResource(R.color.some_color);
回答2:
Use getChildAt(index) from ViewGroup to get View.
来源:https://stackoverflow.com/questions/26335655/how-to-get-a-listviews-child-view-at-specific-index