Why BaseAcivity

We all know that we need to create an Activity when developing an Android application, but many times our application has multiple interfaces and each interface has similar content (for example: Toolbar, DrawerLayout, and background operations have common methods. In this case, we write a BaseActivity as the base class for each Activity and manage each Activity in the program.

One line of code implements the Toolbar effect

Activity_main. The XML code

<?xml version="1.0" encoding="utf-8"? >
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:background="@android:color/holo_blue_light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm the interface for MainActivity."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>
Copy the code

MainAcitvity. Java code

public class MainActivity extends BaseActivity {

    @Override
    protected int getContentView(a) {
        returnR.layout.activity_main; }}Copy the code

“Get off my back and see things first.”

  • Create BaseActivity

    After the project is created, we can see that AndroidStudio automatically generates the mainactivity. Java and activity_main.xml files for us, and then we create a new Activity named BaseActivity.

  • Modify the activity_base.xml file

    Then open activity_base.xml and replace ConstraintLayout with a vertical LinearLayout. Add two elements, Toolbar and FrameLayout.

    Note: Since the Toolbar replaces the ActionBar, we first remove the ActionBar. We hide it by setting the Application theme to hide the ActionBar for all interfaces in the project.

<?xml version="1.0" encoding="utf-8"? >
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BaseActivity"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="? attr/actionBarSize"
        android:background="? attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>
Copy the code
  • Modify the baseActivity. Java file

    Next, open the baseActib. Java file and make BaseActivity inherit AppCompatActivity, modifying the code as follows

    Protected abstract int getContentView(); Is an abstract method, so we’re going to make BaseActivity an abstract class. Why change it to an abstract class? The simple reason is that a class is not allowed to have an abstract method. In order to have an abstract method, the class must be abstract. And then again, you might ask, why abstraction? Are you a hundred thousand why? Since we want the interface of other activities to be displayed in BaseActivity, we must implement this method. If we set it to a normal method, we may forget to call this method when writing code, and the interface will not be displayed. So we need abstract methods, so that every Activity that inherits BaseActivity must override the getContentView() method.

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        initView();
    }

    private void initView(a) {
        // Bind the control
        Toolbar toolbar = findViewById(R.id.toolbar);
        FrameLayout container = findViewById(R.id.container);
        // Initialize the Toolbar
        toolbar.setTitle("I'm the Toolbar for BaseActivity.");
        setSupportActionBar(toolbar);
        // Parse the layout file that inherits BaseActivity into the container so that BaseActivity can display the layout file of MainActivity
        LayoutInflater.from(this).inflate(getContentView(), container);
    }

    /** * Get the resource ID of the layout file to display content **@returnResource ID */ of the displayed content interface
    protected abstract int getContentView(a);

}

Copy the code
  • Open the activity_main. XML file, and change the background color of the parent layout so that we can distinguish between the MainActivity layout file and the BaseActivity layout file. And then I’m going to add a TextView, for the same reason that I changed the background color.
<?xml version="1.0" encoding="utf-8"? >
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:background="@android:color/holo_blue_light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm the interface for MainActivity."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>
Copy the code
  • Modify the mainActivity.java file so that MainActivity inherits BaseActivity and overwrites the getContentView() method, then deletes the onCreate() method. Return the current layout resource ID to the BaseActivity using the getContentView() method. Let the BaseActivity load the layout file.
public class MainActivity extends BaseActivity {

    @Override
    protected int getContentView(a) {
        returnR.layout.activity_main; }}Copy the code
  • Run the project

    Now you run the project. We didn’t add the ToolBar to the Layout of the MainActivity, but the effect of running the ToolBar is that it already exists.

    You can now implement the Toolbar effect in a single line of code. Now you might be wondering, what if I want to change the title and add buttons to the Toolbar? Well, it’s easy. Let’s keep going.

  • We add another abstract method to the BaseActivity and call the abstract method we wrote at the point where we initialize the Toolbar.

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        initView();
    }

    private void initView(a) {
        // Bind the control
        Toolbar toolbar = findViewById(R.id.toolbar);
        FrameLayout container = findViewById(R.id.container);
        // Initialize the Toolbar
        toolbar.setTitle(setTitle());
        setSupportActionBar(toolbar);
        // Parse the layout file that inherits BaseActivity into the container so that BaseActivity can display the layout file of MainActivity
        LayoutInflater.from(this).inflate(getContentView(), container);
    }

    /** * Get the resource ID of the layout file to display content **@returnResource ID */ of the displayed content interface
    protected abstract int getContentView(a);

    /** * Set the title **@returnThe title name to display */
    protected abstract String setTitle(a);

}
Copy the code
  • To modify mainActivity.java, we override the setTitle() method as before and enter the title we want to display in the return value
public class MainActivity extends BaseActivity {

    @Override
    protected int getContentView(a) {
        return R.layout.activity_main;
    }

    @Override
    protected String setTitle(a) {
        return "I'm the title of the MainActivity."; }}Copy the code

At this time, run the following your program will appear you set the title.

  • Let’s show the back button to the Toolbar and get an instance of the ActionBar by going to getSupportActionBar(). To invoke the ActionBar setDisplayHomeAsUpEnabled (true) method to return button displayed.

    The leftmost button of the Toolbar, called HomeAsUp, is hidden by default, and its icon is a return arrow. There is also a setNavigationcon() method to set ICONS, which you can find in the Toolbar documentation

private void initView(a) {
        // Bind the control
        Toolbar toolbar = findViewById(R.id.toolbar);
        FrameLayout container = findViewById(R.id.container);
        // Initialize the Toolbar
        toolbar.setTitle(setTitle());
        setSupportActionBar(toolbar);
        // Parse the layout file that inherits BaseActivity into the container so that BaseActivity can display the layout file of MainActivity
        LayoutInflater.from(this).inflate(getContentView(), container);
        // Display the back button
        ActionBar actionBar = getSupportActionBar();
        if(actionBar ! =null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        / / initialization
        init();
    }
Copy the code
  • Define an interface and declare it and I’ll show you the code snippet in a screenshot

  • Set the listener event to open the mainActivity.java file, override the init() method, and call the setBackOnClickListener() method of the parent class.

    Here I use lambda expressions, which are only supported in Java 8. The default project does not support this, and you need to declare this in build.gradle.

	@Override
    protected void init(a) {
        setBackOnClickListener(() ->
                Toast.makeText(this."Hit the back button.", Toast.LENGTH_SHORT).show()
        );
    }
Copy the code
  • Run the app

The last

Now that you have a simple understanding of BaseActivity, it depends on your project how to use it. It is not necessary to write BaseActivity and inherit BaseActivity in your project. I’m just going to share my understanding of BaseActivity with you. Maybe you still don’t understand after reading this article, here I want to say sorry, maybe some things are not easy to understand or the explanation is wrong, please give me more advice, I will accept and timely correct (even if I made a mistake).

Demo Github address: github.com/lmx0206/Bas… Gitee for Demo: gitee.com/Leungmx/Bas…