如何使用回调接口从Mainactivity到Fragment进行通信? [英] How to communicate from Mainactivity to Fragment using callback interface?

查看:103
本文介绍了如何使用回调接口从Mainactivity到Fragment进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有四个菜单的导航抽屉,每个菜单都有自己的片段 ,第一个片段内有带有2个片段的View pager滑动标签,

I'm having navigation drawer with four menu's and each menu has own fragments , Inside first fragment has view pager sliding tab with 2 fragments,

Activity_main.xml

Activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/drawer_layout"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout  
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/white"
                app:tabIndicatorHeight="4dp" />

        </android.support.design.widget.AppBarLayout>

////////////// Here I'm replacing each fragments ////////////////
        <FrameLayout   
            android:id="@+id/main_content_framelayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|bottom"
            android:layout_margin="@dimen/fab_margin"
            android:src="@drawable/ic_done"
            android:visibility="gone"/>

    </android.support.design.widget.CoordinatorLayout>


        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_view"/>

    </android.support.v4.widget.DrawerLayout>

ManinActivity- DrawerSelection

ManinActivity- DrawerSelection

 public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass = null;

        switch (menuItem.getItemId()) {
            case R.id.nav_home:
                fragmentClass = Home_Tab_Fragment.class;
                break;
            case R.id.nav_myorders:
                fragmentClass = SecondFragment.class;
                break;
            case R.id.nav_myoffers:
                fragmentClass = ThirdFragment.class;
                break;
            case R.id.nav_notification:
                fragmentClass = FourthFragment.class;
                break;

        }

                fragment = (Fragment) fragmentClass.newInstance();
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.main_content_framelayout, fragment).commit();
                mDrawerLayout.closeDrawers();

}

HomeTabFragment

HomeTabFragment

public class Home_Tab_Fragment extends Fragment {

    private FragmentActivity myContext;
    ViewPager viewPager;
    TabLayout tabLayout;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.layout_viewpager, container, false);
          viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SlidingTabAdapter adapter = new SlidingTabAdapter(getChildFragmentManager());
        adapter.addFragment(new FirstTabFragment(), "First TAB");
        adapter.addFragment(new SecondTabFragment(), "Second Tab");
        viewPager.setAdapter(adapter);
        tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
        tabLayout.setVisibility(View.VISIBLE);
        tabLayout.setupWithViewPager(viewPager);
    }

}

SlidingTabAdapter

SlidingTabAdapter

public class SlidingTabAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

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

    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}

layout_viewpager.xml

layout_viewpager.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

FirstFragment

FirstFragment

public class FirstTabFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        getActivity().setTitle("Foodies");
        return rootView ;
    }

  public void updateFirstFragmentValues(){
      //Doing some operations
  }

}

在MainActivity内部,我想调用FirstTabFragment方法[updateFirstFragmentValues()]

我尝试在FirstTabFragment中添加TAG,

I tried adding TAG in FirstTabFragment ,

public static final String TAG ="FirstTabFragment.TAG";

然后我像下面那样在MainActivity中调用,但是Fragment总是为空.

Then I invoked in MainActivity like below , but Fragment always null.

 public void invokeMethodFromFirstTabFragment() {
        FragmentManager fm = this.getSupportFragmentManager();
        FirstTabFragment fb=(FirstTabFragment)fm.findFragmentByTag(FirstTabFragment.TAG);
        if (null != fb) {
            fb.updateFirstFragmentValues();
        }else{
            L.m("Fragment is null===========");
        }
    }

请注意,如何从"MainActivity"内部调用"FirstTabFragment"方法

Kindly advise , How to call "FirstTabFragment" method from inside "MainActivity"

请注意,FirstTabFragment没有直接添加到MainActivity, 它是通过"Home_Tab_Fragment"添加的.

Please note FirstTabFragment is not added directly to MainActivity , its added through "Home_Tab_Fragment".

推荐答案

好了,阅读您的所有响应后,我发现您只需要在创建数据时将数据传递给片段并能够执行某些Fragment的响应即可.方法.好的,很简单:

Alright, reading all of the responses of yours, I get that you just simply need to pass data to a fragment upon creation and be able to execute some of Fragment's methods. Ok, simple enough:

public interface IMessageFragment {
  /**
   * Method to receive new message text
   * @param text Message text to receive
   */
   void updateMessageText(String text);
}

MessageFragment

public class MessageFragment extends Fragment implements IMessageFragment {
  /**
   * Bind views using ButterKnife
   */
  @BindView(R.id.textView) TextView mTextView;

  /**
   * Bundle data
   */
  private String mMessageText;

  /**
   * Unique id of bundle data
   */
  private static final String MESSAGE_EXTRA_KEY = "f_message";

  /**
   * New fragment pattern. This is pretty much all the magic PLUS this
   * looks by far better than `new Fragment()` upon instatiation
   */
  public static MessageFragment newFragment(String message) {
      // 1. Create new fragment
      MessageFragment auctionFragment = new MessageFragment();
      // 2. Create bundle for fragment params
      Bundle args = new Bundle();
      // 3. Put position
      args.putString(MESSAGE_EXTRA_KEY, message);
      // 4. Set arguments
      auctionFragment.setArguments(args);
      return auctionFragment;
  }


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

      /**
       * Bind views
       */
      ButterKnife.bind(this, view);

      // Update UI
      updateUI();

      return view;
  }

  /**
   * Method to update value of mTextView
   */
  private void updateUI() {
      if(!mMessageText.equals("")) {
          mTextView.setText(mMessageText);
      }
  }

  @Override
  public void updateMessageText(String text) {
      mMessageText = text;
      updateUI();
  }
}

内容非常简单,并且仅出于良好的代码风格和支持设计模式而存在接口.

Stuff is pretty simple and the interface exists only for good code style and to support design patterns.

这篇关于如何使用回调接口从Mainactivity到Fragment进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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