android – 使用ViewPager从Activity到Fragment的通信

我有一个Activity和两个片段用于包含viewpager的tablayout.

现在我可以通过实现谷歌的指南回调界面从片段到活动进行通信.但是,我怎样才能将其他方式从活动传达到片段?如果活动(外部事件)中发生了某些事情,我想更新片段.我设法得到了Frag1片段

MyFragmentPagerAdapter a = (MyFragmentPagerAdapter) viewPager.getAdapter();
Frag1 frag = (Frag1) a.getItem(0);

但是当我在frag上调用公共方法时,我得到一个IllegalStateException:片段没有附加到Activity可能是因为getItem(0)返回了一个新的Frag1实例而且还没有附加…是否有人可以为此提供一个干净的解决方案整个Viewpager – >片段交流的活动?

一些代码给你:

在活动中:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null) {
            viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
        }

        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        if (tabLayout != null) {
            tabLayout.setupWithViewPager(viewPager);
        }
}

活动布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context="com.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"/>
</LinearLayout>

MyFragmentPagerAdapter:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    final int PAGE_COUNT = 2;
    private String tabTitles[] = new String[] { "tab1", "tab2" };

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return Frag1.newInstance(position + 1);
            case 1:
                return Frag2.newInstance(position + 1);
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}

Frag1:

public class Frag1 extends Fragment {
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    private onFrag1InteractionListener mListener;

    public Frag1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment Frag1.
     */
    public static Frag1 newInstance(int page) {
        Frag1 fragment = new Frag1();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPage = getArguments().getInt(ARG_PAGE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_1, container, false);
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof onFrag1InteractionListener) {
            mListener = (onFrag1InteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement onFrag1InteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface onFrag1InteractionListener {
        // TODO: Update argument type and name
        void onFrag1Interaction(Action action);
    }

最佳答案 您需要设置一些事件侦听器逻辑,其中片段注册其所需事件的活动.片段应在创建时注册,并在销毁时注销.

然后,当事件发生时,活动将通过已注册的侦听器列表并通知它们事件.

我在this answer中给出了一个详细的例子.

您可以使用事件总线库来简化活动和片段之间的某些连接.

点赞