How To Use Same LinearLayout In Different Activities

463 views Asked by At

I want to use same LinearLayout in different activities. Selected LinearLayout's id in picture is previewLinear. What I want to do is, use previewLinear in a different activity. I have A and B activities. Firstly I do some changes for previewLinear in activity A (adding border, slice it to pieces etc.) programmatically and I want to copy whole previewLinear to B activity.

pencerebol.xml enter image description here

What I tried is;

A Activity: (container is static)

...
setContentView(R.layout.pencerebol);
...
container = (LinearLayout) findViewById(R.id.previewLinear);
        container.setBackground(getResources().getDrawable(R.drawable.border));

B Activity:

...
setContentView(R.layout.pencerebol);
container = (LinearLayout) findViewById (R.id.previewLinear);
container = A.container; // I know that this line is completely wrong but this is what i want to do.

Thanks in advice.

2

There are 2 answers

6
Anton Kovalyov On BEST ANSWER

If I got it right you want to make LinearLayout from B activity look same as in A activity.

You can create method in A activity

static void createLinearLayout(LinearLayout layout){
    layout.setBackground(getResources().getDrawable(R.drawable.border));
    ...
} 

Then call it in B activity

A.createLinearLayout(container);
5
blueware On

You can use the <include> property in your XML files, you only create one layout and include it in your other activities/fragments, this is an example of that:

create a xml for your previewLinear layout, name it as:

layout_preview_linear.xml

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

and then in your activity A or B, you can include it as the following:

activity_a.xml

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

        <include
            android:id="@+id/previewLayout"
            layout="@layout/layout_preview_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

You also can use that layout in your JAVA code as well, hope this will help you.