How to display one activity inside another in Android?
android, android-activity, android-linearlayout
Solution
Use one layout for several activities
Layout instance is inflated for each activity using a `setContentView` method, usually in `onCreate`:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_common_layout);
}
So there's no problem to use the same `XML` layout for different activities.
Display one activity inside another
You can use a `Fragment` API to complete the task. See full details in developer's guide.
Declare a layout like that 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 a `MyFragment` class and load it when appropriate.
Create fragments yourself. Do not define the `Fragment` in `XML` layout:
<?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 your parent `Activity` is created you can add a new `Fragment` in this way:
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 like this:
public class MyFragment extends Fragment {
...
}
If you're targeting below Android 3.0, consider using support package for that.
Problem
I have one activity and want to display another inside it. Here's 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 inner `LinearLayout` on button click?