如何从 MainActivity 调用 Fragment 中定义的方法
How to call method defined in Fragment from MainActivity
我正在尝试调用片段中定义的方法。例如我在片段
中有以下方法
public void testMethod(){
Toast.makeText(getActivity(),"Hi",Toast.LENGTH_SHORT).show();
}
我想从 MainActivity 调用这个方法。我定义如下。
private void callMethodFromFragment() {
TestFragment testFragment = new TestFragment();
testFragment.testMethod();
}
我收到以下错误
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:4000)
at android.view.View.performClick(View.java:4754)
这是我的 activity_main.xml 布局
<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>
在将片段添加到 activity 时为片段添加标签,如下所示:
getFragmentManager().beginTransaction().add(R.id.content_frame, testFragment, "myTag").commit();
然后你可以通过标签获取片段:
TestFragment fragment = (TestFragment) getFragmentManager().findFragmentByTag("myTag");
if (fragment) {
fragment.testMethod();
}
我正在尝试调用片段中定义的方法。例如我在片段
中有以下方法public void testMethod(){
Toast.makeText(getActivity(),"Hi",Toast.LENGTH_SHORT).show();
}
我想从 MainActivity 调用这个方法。我定义如下。
private void callMethodFromFragment() {
TestFragment testFragment = new TestFragment();
testFragment.testMethod();
}
我收到以下错误
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:4000)
at android.view.View.performClick(View.java:4754)
这是我的 activity_main.xml 布局
<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>
在将片段添加到 activity 时为片段添加标签,如下所示:
getFragmentManager().beginTransaction().add(R.id.content_frame, testFragment, "myTag").commit();
然后你可以通过标签获取片段:
TestFragment fragment = (TestFragment) getFragmentManager().findFragmentByTag("myTag");
if (fragment) {
fragment.testMethod();
}