【问题标题】:How to call method defined in Fragment from MainActivity如何从 MainActivity 调用 Fragment 中定义的方法
【发布时间】:2015-04-20 18:44:46
【问题描述】:

我正在尝试调用片段中定义的方法。例如我在片段中有以下方法

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$1.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>

【问题讨论】:

  • This 可能会有所帮助
  • 我看到你可以从 id 或 tag 访问它。但我没有在 layout 中定义片段。我只有 FrameLayout 和 ListView
  • 能否请您显示更多代码以及您拥有哪些布局文件?

标签: android android-intent android-fragments android-activity


【解决方案1】:

在将片段添加到活动时给它一个标签,如下所示:

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

然后就可以通过标签获取片段了:

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

【讨论】:

  • 根据我的布局文件,R.id.fragment_container 应该是什么?应该是 content_frame 还是 left_drawer?
猜你喜欢
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 2018-08-22
  • 1970-01-01
相关资源
最近更新 更多