如何从MainActivity调用Fragment中定义的方法 [英] How to call method defined in Fragment from MainActivity
本文介绍了如何从MainActivity调用Fragment中定义的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试调用Fragment中定义的方法.例如我在片段中有以下方法
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();
}
我想从MainActivity调用此方法.我将其定义如下.
I want to call this method from MainActivity. I defined it as below.
private void callMethodFromFragment() {
TestFragment testFragment = new TestFragment();
testFragment.testMethod();
}
我收到以下错误
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)
这是我的activity_main.xml布局
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>
推荐答案
将片段添加到活动中时,给片段一个标签,如下所示:
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();
}
这篇关于如何从MainActivity调用Fragment中定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文