简体   繁体   English

Viewpager“ ViewGroup”更改背景颜色运行时

[英]Viewpager “ViewGroup” change background color runtime

I have got a simple viewpager with a few views. 我有一些简单的viewpager。 I have a button in each view that once clicked it should change the background color of the view to a pre-determined color. 我在每个视图中都有一个按钮,一旦单击它,应将视图的背景色更改为预定的颜色。

In my instantiateItem I have the following: 在我的InstantiateItem中,我有以下内容:

public CustomPagerAdapter(Context context) {
    mContext = context;
}

@Override
public Object instantiateItem(ViewGroup collection, int position) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);

    PopulateView(position);
    collection.addView(layout);
    return layout;
}

I have another function (populateView) that takes care of drawing my view and creating the button. 我还有另一个函数(populateView),它负责绘制视图并创建按钮。

I was thinking of holding on to an instance of "ViewGroup layout" as class variable and use it but clicking the button in view 1 would cause a random view (say view 2)'s background color to change. 我正在考虑将“ ViewGroup布局”的实例作为类变量使用并使用它,但是单击视图1中的按钮将导致随机视图(例如视图2)的背景色发生变化。

So I kept a copy of "ViewGroup collection" and used 所以我保留了“ ViewGroup集合”的副本,并使用了

collection.getChildAt(position).setBackgroundColor(mContext.getResources().getColor(sky));

but the app would crash on the last view color change with the error java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference 但是应用程序将在最后一次视图颜色更改时崩溃,并出现错误java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.view.View.setBackgroundColor(int)'

collection = {ViewPage@4834} "android.support.v4.view.ViewPager{e1f06a0 VFED..... ......ID 0,0-1080,1536 #7f0d0091 app:id/viewpager}"
mContext = {MainActivity@4835}
position = 2

The strangest thing is when I look inside "collection", and expand the "Children" there are only 2 children listed. 最奇怪的是,当我查看“集合”内部并展开“孩子”时,仅列出了2个孩子。 There should be 3. I can't understand why this is. 应该是3。我不明白为什么会这样。

Can someone please help me? 有人可以帮帮我吗?

Well you need to give the position at which to add the child. 好吧,您需要指定添加子项的位置。 See here 看这里

@Override
public Object instantiateItem(ViewGroup collection, int position) {

    .....


    collection.addView(layout, 0);
    return layout;
}

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

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