简体   繁体   English

如何从活动中调用片段方法

[英]How to call fragment method from activity

I'm populating fragments in a tablayout. 我在TabLayout中填充片段。 I have a method in one of my fragments, and i want to call it from an activity. 我的一个片段中有一个方法,我想从一个活动中调用它。 But when i tried to have reference of the fragment by doing like this Fragment myFragment = (Fragment ) getSupportFragmentManager().findFragmentById(R.id.my_fragment) , myFragment is null. 但是当我尝试通过像这样的Fragment myFragment = (Fragment ) getSupportFragmentManager().findFragmentById(R.id.my_fragment)来引用片段时, Fragment myFragment = (Fragment ) getSupportFragmentManager().findFragmentById(R.id.my_fragment)myFragment为null。 I'm new to android. 我是android新手。 (Sorry for the bad english) (对不起,英语不好)

My code so far. 到目前为止,我的代码。

public class DashboardActivity extends AppCompatActivity {

    private ViewPager pager;
    private TabLayout tabLayout;
    private Toolbar dashboardToolbar;

    public static int position;

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

        HomeFragment myFragment = new HomeFragment ();
        if(getSupportFragmentManager().findFragmentById(R.id.homeFragment) == null) {
                       getSupportFragmentManager().beginTransaction()
                    .add(R.id.homeFragment, myFragment).commit();

        }


        pager = (ViewPager) findViewById(R.id.view_pager);
        setupViewPager(pager);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(pager);

        pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
               // Toast.makeText(DashboardActivity.this, "tabSelected:  " + tab.getText()+" "+ tab.getPosition(), Toast.LENGTH_SHORT).show();
                // no where in the code it is defined what will happen when tab is tapped/selected by the user
                // this is why the following line is necessary
                // we need to manually set the correct fragment when a tab is selected/tapped
                // and this is the problem in your code
               pager.setCurrentItem(tab.getPosition());
               position = tab.getPosition();

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
              //  Toast.makeText(DashboardActivity.this, "tabReSelected:  " + tab.getText(), Toast.LENGTH_SHORT).show();

                position = tab.getPosition();

                // Reload your recyclerView here
            }
        });


    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "FOR YOU");
        adapter.addFragment(new NotificationFragment(), "NOTIF");
        adapter.addFragment(new ChatFragment(), "CHAT");
        adapter.addFragment(new ProfileFragment(), "PROFILE");
        viewPager.setAdapter(adapter);
    }

}

Fragment 分段

  public class HomeFragment extends Fragment {
        // Objects Declaration


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


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

public void myMethod(){ //method to be called
//do something
}
     }

Activity 活动

public class MyActivity extends AppCompatActivity {



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


                HomeFragment myFragment= (HomeFragment ) getSupportFragmentManager().findFragmentById(R.id.homeFragment);

                    if(myFragment!= null) {
                        Toast.makeText(ActivityFilter.this, "Not null.", Toast.LENGTH_SHORT).show();
 home.myMethod(); // this line is not accessed since myFragment is null

                    }else{
                        Toast.makeText(ActivityFilter.this, "Null fragment.", Toast.LENGTH_SHORT).show();
                    }

    }

}

You should use a Callback. 您应该使用回调。

Create a public interface in your fragment. 在您的片段中创建一个公共接口。

public interface iCommunicateListener{
    void communicate(String msg);
}

You also have to make the activity your listener. 您还必须使该活动成为您的听众。 (You can have many listeners, but fragments are supposed to be reusable, so if you have many listeners it will not be as reusable as it could and should be) (您可以有很多侦听器,但是片段应该是可重用的,因此,如果您有很多侦听器,那么它们将不会如应有的那样被重用)

private iCommunicateListener listener;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        listener = (iCommunicateListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement iCommunicateListener");
    }
}

Now you have active listener. 现在您已经有了活跃的侦听器。 In your onClicks or whenever you want send information to your activity, you have to call listener.communicate("doSomething"); 在您的onClicks中或您希望向活动发送信息时,您必须调用listener.communicate("doSomething"); ;。

Your Activity must implement the iCommunicateListener. 您的活动必须实现iCommunicateListener。

After implementation of the method communicate you can choose your logic for the different Strings or whatever you want to send through the callback. 在实现方法通信之后,您可以为不同的String或要通过回调发送的任何内容选择逻辑。 There are many other ways for communication between Activities and Fragments, but since you are just beggining learn this one. 活动和片段之间还有许多其他的交流方式,但是由于您只是在开始学习而已。 After you implement it and you see the result you can take a look at this library which will definately help you in your android development. 在实现它并看到结果后,您可以看一下该库,它将最终对您的android开发有所帮助。 EventBus 事件总线

With EventBus you will not have to use the callbacks which will make your fragments even more reusable and flexible, but first learn the normal Callbacks. 使用EventBus,您将不必使用回调,这将使您的片段更加可重用和灵活,但首先请学习常规的回调。 It is a basic pattern and you will use it in many different situations. 这是一种基本模式,您将在许多不同的情况下使用它。 More on Fragments: Fragments Hope this helps! 有关碎片的更多信息: 碎片希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM