How to display one action inside another in Android?

I have one action and you want to display another in it. Here is my layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> </LinearLayout> </LinearLayout> 

How can I display an Activity in an internal LinearLayout when a button is clicked?

+4
source share
1 answer

Use one layout for multiple actions.

A layout instance is inflated for each activity using the setContentView method, usually in onCreate :

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_common_layout); } 

Thus, there is no problem using the same XML layout for different actions.

Display one action inside another

You can use the Fragment API to complete the task. See the Developer's Guide for more details.

  • Declare such a layout and Android will create fragments for you:

     <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment android:name="com.example.MyFragment" android:id="@+id/my_fragment" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout> 

    Then create the MyFragment class and load it when necessary.

  • Create fragments yourself. Do not define the Fragment layout in XML :

     <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/my_parent_layout"> </LinearLayout> 

    After creating the parent Activity you can add a new Fragment as follows:

     FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); MyFragment fragment = new MyFragment(); fragmentTransaction.add(R.id.my_parent_layout, fragment); fragmentTransaction.commit(); 

    Here MyFragment is defined as follows:

     public class MyFragment extends Fragment { ... } 

If you are setting up Android 3.0, consider using a support package .

+8
source

Source: https://habr.com/ru/post/1414602/


All Articles