Changing the xml by java

Asked

Viewed 123 times

1

I was wondering if there’s a way I could change the layout="@layout/app_bar_main" of <include> by java

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>
  • If you prefer, you can try it this way: https://stackoverflow.com/a/18999694/4508758

1 answer

3


First it is necessary to include a id to his <include>.

 <include
    android:id="@+id/main_container"
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Then you can do it this way using the LayoutInflater:

RelativeLayout main= (RelativeLayout) findViewById(R.id.main_container); 
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.seu_layout, null);
main.removeAllViews();
main.addView(layout);

However, use the ViewStub in this situation may be more advantageous than <include>. See below for an example:

<ViewStub
    android:id="@+id/main_container"
    android:inflatedId="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

So in class:

ViewStub stub = (ViewStub) findViewById(R.id.main_container);
stub.setLayoutResource(R.layout.seu_layout);
View inflated = stub.inflate();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.