Changing the xml by java

2

I wanted to know if there is a way I can change 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>
    
asked by anonymous 05.03.2018 / 03:17

1 answer

4

First of all you need to include id to your <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 this using 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, using ViewStub in this situation may be more advantageous than <include> . Here is an example:

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

So in the class:

ViewStub stub = (ViewStub) findViewById(R.id.main_container);
stub.setLayoutResource(R.layout.seu_layout);
View inflated = stub.inflate();
    
05.03.2018 / 04:59