简体   繁体   中英

How to pass data from an activity to a fragment in TabHost?

I have a page divided like this: there is the "Main" layout which holds a fragment

<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" />

Inside that fragment in an external layout I've created a TabHost like this:

<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>

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

You can call the method of First.class from the Main.class by simply using this code. Inside your Main.class

new First.method();

You should define a public method inside First fragment and invoke when push button on MainACtivity. Be aware of that fragment is currently shown if you want to update some fragment's UI element.

Take a look at Fragments developer guide .

Likewise, your activity can call methods in the fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag().

From your Activity, get the Fragment and call the method.

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.first);
if(fragment != null){    
  ((First)fragment).yourMethod();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM