How to get a ListView's child view at specific index

风流意气都作罢 提交于 2020-01-05 13:32:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!