android custom title bar

Posted by arbelo on Sun, 15 Dec 2019 18:06:38 +0100

Want to customize a title block, there is a simple way, the introduction of layout files can be.

Let's imitate a simple title bar, that is, a button on the left and right, and a text in the middle. That is to say, we only need two buttons and one TextView

1. Create a new layout title.xml, and the code is as shown in the figure:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/title_bg">//Background map of the whole layout

    <Button
        android:id="@+id/title_back"
        android:layout_width="77dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/qod"
        android:text="Return"
        android:textColor="@android:color/darker_gray" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="214dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="7dp"
        android:gravity="center"
        android:text="Text Center"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp" />

    <Button
        android:id="@+id/title_set"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/gwf"
        android:textColor="@android:color/darker_gray" />
</LinearLayout>

In this file, we use LinearLayout, two buttons and one text. We use three pictures to specify a background for the layout and space. You can also directly fill in the color. Title bg.png, qod.png and gwf.png are respectively used for the title bar, return button and set button background.

The layout pattern obtained from the above documents is as follows:

2. Don't forget to hide the title bar of the system in mainactivity. The code is as follows:

 getSupportActionBar().hide();

3. You can register the listener of the button in mainactivity to achieve some effect. The code is as follows:

Button back = (Button) findViewById(R.id.title_back);
back.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
                Toast.makeText(MainActivity.this , "Return key is clicked" , Toast.LENGTH_SHORT).show();
            }
        });

4. Run the program, click the back button, and the effect picture is as follows (for others, just pay attention to the effect of the title bar)

 

 

Topics: Android xml encoding