在 ViewPager 中从 Activity 更新片段 [英] Updating fragments from Activity in a ViewPager

查看:17
本文介绍了在 ViewPager 中从 Activity 更新片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 开发新手,非常感谢您提供帮助.

I'm new to Android developing and I would really appreciate some help here.

我正在使用一个包含 TextView 的片段,并且我正在使用同一个 MyFragment 类的 5 个实例.

I'm using a fragment that contains a TextView and I'm using 5 instances of the same MyFragment class.

在活动中,我有一个按钮和一个 ViewPager,我需要该按钮来更新所有片段实例的内容,无论何时单击它.

In the activity, i got a button and a ViewPager, and I need the button to update all the fragment instances content, whenever its clicked.

这是活动

public class MainActivity extends FragmentActivity {

final static String[] CONTENT = {"a", "b"};
ViewPager pager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    List<MyFragment> fragments = new Vector<MyFragment>();
    for(int i = 0; i < 5; i++){
        MyFragment fragment = new MyFragment(CONTENT);
        fragments.add(fragment);
    }
    PagerAdapter adapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
    pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setAdapter(adapter);

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //method that isn't working
            PagerAdapter adapter = (PagerAdapter)pager.getAdapter();
            for(int i = 0; i < 5; i++){
                MyFragment fragment = (MyFragment) adapter.getItem(i);
                fragment.textView.setText(fragment.content[1]);
            }
        }
    });
}
}

片段

public class MyFragment extends Fragment{

String[] content;
    TextView textView;

public MyFragment(String[] content) {
    this.content = content;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_content, container, false);
    textView = (TextView) view.findViewById(R.id.textView1);
    textView.setText(content[0]);
    return view;
}

}

还有 FragmentPagerAdapter

And the FragmentPagerAdapter

public class PagerAdapter extends FragmentPagerAdapter{

List<MyFragment> fragments;

public PagerAdapter(FragmentManager fm, List<MyFragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

@Override
public Fragment getItem(int arg0) {
    return fragments.get(arg0);
}

@Override
public int getCount() {
    return fragments.size();
}

}

每当我尝试从适配器访问小于 adapter.getCurrentItem() - 1 或大于 adapter.getCurrentItem() + 1 的片段时,OnClick 方法都会给我一个 NullPointerException.

The OnClick method gives me a NullPointerException whenever i try to access a fragment from the adapter which is less than adapter.getCurrentItem() - 1, or more than adapter.getCurrentItem() + 1.

知道如何同时更新所有片段吗?

Any idea on how to update all the fragments at the same time?

提前致谢.

推荐答案

更新这些片段的最简单方法是使用您的代码并将 ViewPager 在内存中保存的片段数设置为总片段数 - 1(因此无论您在哪个页面,所有片段都有效).在你的情况下:

The easiest way to update those fragments is to use your code and set the number of fragments that the ViewPager holds in memory to the number of total fragments - 1(so all fragments are valid no matter at what page you are). In your case:

pager.setOffscreenPageLimit(4); // you have 5 elements

您仍然可以使用我评论中的方法和方法 onPageScrollStateChanged(因此更新将在用户开始滑动的那一刻开始)查看用户何时开始滑动寻呼机并更新当前可见片段的左侧和右侧的片段,但这会有点难以正确,所以我建议使用第一个选项.

You can still use the method from my comment with the method onPageScrollStateChanged(so the update will start the moment the user starts swiping) to see when the user is starting to swipe the pager and update the fragments to the left and right of the currently visible fragment, but this will be a bit difficult to get right so I recommend to go with the first option.

关于包含片段的代码的一些要点:

Some points regarding your code containing fragments:

如果您嵌套片段类,请将其设为静态,这样您就不会将其绑定到活动对象.除了默认的之外,不要为 Fragment 创建构造函数.如果框架需要重新创建片段,它将调用默认构造函数,如果它不可用,则会抛出异常.例如,尝试更改手机/模拟器的方向并查看会发生什么(这是 Android 将重新创建片段的情况之一).最后,为 ViewPager 的适配器使用自定义名称,您使用 PagerAdapter 这是 FragmentViewPager 的超类的名称,它非常让阅读您的代码的人感到困惑.

If you nest the fragment class make it static so you don't tie it to the activity object. Don't create a constructor for a Fragment besides the default one. If the framework needs to recreate the fragment it will call the default constructor and if it is not available it will throw an exception. For example, try to change the orientation of the phone/emulator and see what happens(this is one of the cases when Android will recreate the fragments). Last, use a custom name for the ViewPager's adapter, you use PagerAdapter which is the name of the super class of FragmentViewPager and it's very confusing for someone reading your code.

如果您需要将数据传递给 Fragment,您可以使用如下创建方法:

If you need to pass data to the Fragment you could use a creation method like the one below:

public static MyFragment newInstance(String text) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putString("content", text);
        f.setArguments(b);
        return f;
    }

通过使用 getArguments().getString("content");

这篇关于在 ViewPager 中从 Activity 更新片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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