[英]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.