theJava
theJava

Reputation: 15034

Can i load a specific layout at runtime?

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

If my orientation changes, i don't want the entire layout to be re-loaded instead specific section/layout to be re-loaded/re-created for portrait mode.

Update:

I have placed this inside my mainifest => android:configChanges="orientation|screenSize|keyboardHidden" , so the whole activity is not re-created again. But a certain section in my activity needs to be different for potrait and landscape mode.

Upvotes: 0

Views: 134

Answers (5)

Blackbelt
Blackbelt

Reputation: 157447

I think you should let Android do its work. When the device rotate the Activity is destroyed and recreated. That means the onCreate is called. I will check the orientation inside the onCreate and choose the correct layout.

Upvotes: 0

bugraoral
bugraoral

Reputation: 2670

It's automatic. If you create a folder layout-land and create your new layout with the "same name"(If it's main.xml in layout folder than it should be main.xml in layout-land also). Then when android recreates your layout when orientation is changed to landscape, it will load the one under layout-land folder.

For further information

Upvotes: 1

Arun C
Arun C

Reputation: 9035

Use include layout

Eg:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width=”match_parent”
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

Now create separate titlebar layout in res/layout and res/layout-land

For more see Use the < include > Tag

Upvotes: 2

Monty
Monty

Reputation: 3215

no need to use onConfigchange().

create two layout folder in res .

layout_land and layout_port and put these given xml's in these layouts .

Here you need to create two layouts with same name

1- layout_change

2- layout_change

in port add new change what you want .

Upvotes: 0

Analizer
Analizer

Reputation: 1644

I don't fully understand your question, but when orientation is changed, your whole activity will be destroyed and reloaded, so every layout will be re-loaded.

Upvotes: 0

Related Questions