A
A
Al2017-04-03 22:08:33
Android
Al, 2017-04-03 22:08:33

How to get rid of code duplication in different activities?

Let's say there is a main activity, its body is described in main_activity_body, in general it looks like this:

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

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- MAIN Activity -->
        <include layout="@layout/main_activity_body" />
    </FrameLayout>

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

</android.support.v4.widget.DrawerLayout>

I want to create a second activity, I describe it in the second_activity_body file, but how can I create it so that I don't do this:
<include layout="@layout/toolbar" />

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- SECOND Activity -->
        <include layout="@layout/second_activity_body" />
    </FrameLayout>

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

</android.support.v4.widget.DrawerLayout>

This is hard code duplication, how to avoid it, how to make things smarter?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Myvrenik, 2017-04-03
@Sanu0074

You can solve this problem with ViewStub :

<ViewStub
    android:id="@+id/lazy_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

And depending on the Activity, inflate the required layout:
ViewStub lazyLayout = (ViewStub) findViewById(R.id.lazy_layout);
lazyLayout.setLayoutResource(R.layout.main_activity_body); // Либо R.layout.second_activity_body
lazyLayout.inflate();

A
Artem Soshnikov, 2017-04-03
@artem90

Create your own class inherited from DrawerLayout and implement the necessary parameters in it. And when building a view file, use your own class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question