如何改变方向时重绘列表视图项目 [英] How to repaint listview items when changing orientation

查看:132
本文介绍了如何改变方向时重绘列表视图项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像Gmail应用进行一些作用:当长期接触的几个列表视图项的背景颜色改变,使用户通知的事情发生了。

I'm trying to perform something like the GMail app does: when long touching several List view items their background colour is changed so that the user notices that something happened.

我的问题是保持视觉上选择(与背景颜色变化)的项目,当设备方向改变。我想这有一点运气:

My problem is to keep those items visually selected (with the background colour changed) when the device orientation is changed. I tried this with little luck:

ListView lv = getListView();
ItemAdapter adapter = (ItemAdapter)lv.getAdapter();
if (adapter == null) return;

for (Item q : mSelectedItems) {
    int position = adapter.getItemPosition(q);
    if (position == -1) continue;

    View itemView = lv.getChildAt(position);
    if (itemView == null) continue;

    itemView.setBackgroundColor(getResources().getColor(R.color.orange));
}

我把从onRestoreInstanceState()回调这个方法,但我收到ItemView控件中的一个空,因为它似乎ListView控件未填充了没有,所以有没有孩子的时刻。我试着和调用从onResume这种方法没有运气。

I call this method from the onRestoreInstanceState() callback, but I receive a null in itemView because it seems that the listView hasn't been filled up yet, so there are no children at the moment. I tried to call this method from the onResume with no luck as well.

什么是实现这一目标的正确方法?

What's the proper way to accomplish this?

推荐答案

我发现我自己的解决方案。做到这一点的正确方法是创建填充视图定制适配器。创建适配器提供上下文,并调用它来获得其背景必须改变的项目(有哪些项目应该绘制这样或那样的方式的信息的活动)。当在列表视图迭代作画,如果当前项目就是其中之一,它漆成不同。例如:

I found the solution by myself. The proper way to accomplish this is the custom Adapter created to fill the view. Create the adapter providing a context (the Activity that has the information of which items should be painted this way or that way) and call it to get the items whose background must be changed. When iterating on the listview to paint, if the current item is one of those, paint it differently. Example:

public View getView(int position, View convertView, ViewGroup parent) {
...
RelativeLayout itemLayout =
        (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.my_layout, parent,
        false);
    if (((MyActivity) mContext).isItemSelected(item)) {
             itemLayout.setBackgroundColor(mContext.getResources().getColor(R.color.orange));
        }
    }

这篇关于如何改变方向时重绘列表视图项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆