Android 如何更新 ViewPager 内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10611018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:21:40  来源:igfitidea点击:

How to update ViewPager content?

androidlistviewandroid-viewpagerpagerindicator

提问by weldsonandrade

i have this PageAdapterwith days of the week, for each pager I have the same Layout. My problem is how update the right listView when change the day. When I change the day the Pager create a new pager and delete other, when this happened my listview point to new pager but not the current. For Example, is wedneyday and I save listview reference, when i change for Tuesday the monday pager is create and Thursday is deleted, and my reference point to last page create(monday) but I'm on tuesday.

PageAdapter在一周中的几天都有这个,对于每个寻呼机,我都有相同的布局。我的问题是如何在更改日期时更新正确的 listView。当我更改寻呼机创建新寻呼机并删除其他寻呼机的日期时,发生这种情况时我的列表视图指向新寻呼机而不是当前。例如,是星期三,我保存了列表视图参考​​,当我更改为星期二时,星期一的寻呼机被创建,星期四被删除,我的参考指向最后一页创建(星期一),但我在星期二。

My pageAdapter:

我的页面适配器:

ListView lvwConfig;

@Override
public Object instantiateItem(View pager, int position) {
    LayoutInflater inflater = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.pager_layout, null);
    lvwConfig = (ListView) v.findViewById(R.id.lvwConfig);
    ((ViewPager) pager).addView(v, 0);

    return v;
}

I want to the ListViewalways point to listview of the current item.

我想ListView始终指向当前项目的列表视图。

回答by julien dumortier

Read this post: PagerAdapter

阅读这篇文章:PagerAdapter

You can implement this function in PagerAdapter:

你可以在 PagerAdapter 中实现这个功能:

public int getItemPosition(Object object){
     return POSITION_NONE;
}

after, you can used this function:

之后,您可以使用此功能:

yourPagerAdapterObject.notifyDataSetChanged();

This method is bad if you have too many views as to display. All the views are always recalculated. But in your case, for some views, it's okay.

如果您有太多视图无法显示,则此方法很糟糕。所有视图总是重新计算。但在你的情况下,对于某些观点,没关系。

回答by Davood Hanifi

Overriding getItemPosition in PagerAdapter is easier, but bit more inefficient. This way, when you call notifyDataSetChanged(), the view pager will remove all views and reload them all. As so the reload effect is obtained. There was another option that suggested by alvarolb, is to setTag()method in instantiateItem()when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag()to find the view you want to update.

在 PagerAdapter 中覆盖 getItemPosition 更容易,但效率更低。这样,当您调用 时notifyDataSetChanged(),视图寻呼机将删除所有视图并重新加载它们。这样就获得了重装效果。alvarolb 建议的另一个选项是setTag()instantiateItem()实例化新视图时使用方法。然后notifyDataSetChanged(),您可以使用findViewWithTag()来查找要更新的视图,而不是使用。