[英]How to pass data from an activity to a fragment in TabHost?
我有一个这样划分的页面:有一个包含片段的“主”布局
<fragment
android:name="com.x.x.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/firstFragment"
tools:layout="@layout/first_fragment" />
在该片段的外部布局中,我创建了一个TabHost,如下所示:
<TabHost
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tabHost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.x.x.First"
tools:layout="@layout/first" />
<fragment
android:id="@+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.x.x.Second"
tools:layout="@layout/second" />
</FrameLayout>
</LinearLayout>
</TabHost>
问题是,当单击“ Main”类中的按钮时,我需要在“ First”类中运行一个方法。
从昨天开始我一直在努力解决这个问题,有什么解决办法吗?
谢谢。
您可以通过使用此代码从Main.class调用First.class的方法。 在您的Main.class内部
new First.method();
您应该在First片段内定义一个公共方法,并在MainACtivity上的按钮按下时调用。 请注意,如果要更新某个片段的UI元素,则当前会显示该片段。
看看Fragments开发人员指南 。
同样,您的活动可以通过使用findFragmentById()或findFragmentByTag()从FragmentManager获取对Fragment的引用来调用片段中的方法。
从您的Activity中,获取Fragment并调用该方法。
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.first);
if(fragment != null){
((First)fragment).yourMethod();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.