How to call method defined in Fragment from MainAc

2019-09-05 10:11发布

问题:

I am trying to call a method defined in a Fragment. e.g. I have the below method in a fragment

public void testMethod(){
        Toast.makeText(getActivity(),"Hi",Toast.LENGTH_SHORT).show();
    }

I want to call this method from MainActivity. I defined it as below.

private void callMethodFromFragment() {
        TestFragment testFragment = new TestFragment();
        testFragment.testMethod();
    }

I get the following error

java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:4000)
            at android.view.View.performClick(View.java:4754)

Here is my activity_main.xml layout

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#fff"/>
</android.support.v4.widget.DrawerLayout>

回答1:

Give your fragment a tag when adding it to the activity like so:

getFragmentManager().beginTransaction().add(R.id.content_frame, testFragment, "myTag").commit();

Then you can get the fragment by tag:

TestFragment fragment = (TestFragment) getFragmentManager().findFragmentByTag("myTag");
if (fragment) {
fragment.testMethod();
}