android - PageAdapter.Instantiate 新项目的时机

标签 android android-viewpager

在下面粘贴的完美运行的代码中,myPagerAdapter 类的 instantiateItem 方法在 int myint = 7 之后执行;操作说明。这给我带来了一个问题,因为我想引用一些 myint = 7 指令所在的 xml 页面,但抛出异常,因为当我尝试进行这些引用时,4 个 xml 页面尚未膨胀。

instantiateItem 被调用了 4 次,它尽职尽责地膨胀每个 xml 页面,但它显然是以某种方式异步完成的,而且为时已晚。在执行 mint = 7 指令(实际上是我的其他计划代码)之前,我需要让页面同步膨胀。我怎样才能做到这一点?怎么回事?

谢谢,加里

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PSContext = this;
    setContentView(R.layout.main);
    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.mysevenpanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
    myPager.setOffscreenPageLimit(4);
    myPager.setOnPageChangeListener(adapter); 

    int myint = 7; //just a debug stop
}   

private class MyPagerAdapter extends PagerAdapter 
    implements ViewPager.OnPageChangeListener {

    public int getCount() {
        return 4;
    }

    public Object instantiateItem(View collection, int position) {

        LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.left;
            break;
        case 1:
            resId = R.layout.gps;
            break;
        case 2:
            resId = R.layout.map;
            break;
        case 3:
            resId = R.layout.right;
            break;
        }

        View view = inflater.inflate(resId, null);

        ((ViewPager) collection).addView(view, 0);

最佳答案

I need to get the pages inflated synchrnously

不支持。

before the mint = 7 instruction (actually my other planned code)is executed

这并不意味着您“需要让页面同步膨胀”。这意味着您需要将这项工作延迟到工作队列的后面,即 PagerAdapter 完成其工作之后。

替换:

mint = 7;

与:

myPager.post(new Runnable() {
  public void run() {
    mint = 7;
  }
});

可能就足够了。

要么那样,要么从 MyPagerAdapter 触发工作,例如在创建页面后在页面上进行工作。

关于android - PageAdapter.Instantiate 新项目的时机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023120/

相关文章:

android - 从 web .vcs 下载将日历事件添加到 Android

android - Android 上的 GridView 滚动问题

android - 使用 BottomBar 和 fragment 容器禁用 Android fragment 重新加载

android - 使用 "android.util.Base64"和 "org.apache.commons.codec.binary.Base64;"的不同编码

java - android 中的 HttpURLConnection 不发送正确的 User-Agent header

android - ViewPagers 的隐式 Z 排序

android - 操作栏 Sherlock - 滑动时选项卡不会改变横向

android - 在 ViewPager 中同步 fragment 滚动

java - 使用 viewPager 滚动所有布局

Android/Firebase - 无法将 java.util.ArrayList 类型的对象转换为类型 **我的对象**