android - 如何在ViewPager中的各个Fragment间传递数据并刷新Fragment界面?
ringa_lee
ringa_lee 2017-04-17 15:00:42
0
3
854

tablayout+viewpager+fragment实现的下图的效果,怎么在各个Fragment中传递数据并刷新界面?

如图中,点击“菜单”中的按钮,如何在购物车中接收并刷新界面。

ringa_lee
ringa_lee

ringa_lee

reply all(3)
阿神

If the Fragment already exists, trying to pass parameters via fragment.setArguments(bundle) will result in an exception:

12-02 00:14:55.375: E/AndroidRuntime(8492): java.lang.IllegalStateException: Fragment already active
12-02 00:14:55.375: E/AndroidRuntime(8492):     at android.support.v4.app.Fragment.setArguments(Fragment.java:548)

My common way to update Fragment is to define a public method for Fragment:

// To update fragment in ViewPager, we should implement a public method for the fragment,
// and do updating stuff in this method.
public void updateDate(Date date) {
    mDate = date;
    mTextView.setText(mDate.toString());
}

Then get the Fragment that needs to be updated, and then call this method.
Considering that you only have 4 Fragments, you can try to use an Array or List to save instances of these 4 fragments in the activity (this method is relatively stupid).
And you need to use FragmentPagerAdapter instead of FragmentStatePagerAdapter, so that when switching pages in ViewPager, the fragment instance will not be destroyed. You can refer to my article on how to update and replace Fragment in ViewPager

PHPzhong

Use proxy mode to implement reverse value transfer.

Activity is equivalent to the parent set of these fragments. It is definitely very easy to operate these fragments in the activity (because the fragments are all new in the activity). So if one of your fragments can get the activity. You can easily operate other fragments.

The simplest way is to add an activity attribute to the fragment. When new fragments are created in the activity, pass activity.this to the fragment.

But generally let the activity implement an interface, such as XXDelegate, and the constructor of the fragment has an XXDelagate. Just pass this (the activity itself) when the activity is created.

大家讲道理

You can use bundle to transfer parameters. You can bring parameters when jumping between two Fragments. To obtain parameters in another Fragment, you only need to use getArguments().getString("key"); the key is defined by yourself. An identifier and parameter form can be implemented as long as the bundle can be passed. This principle is basically the same as Activity
For example:
Bundle bundle=new Bundle();
bundle.putString("key", Projsid) ;
fragment.setArguments(bundle);                        fragment.commit();           

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!