简体   繁体   中英

How to add Text in a custom action bar for Android

I am able to create an actionbar with a custom back button as such:

// Calling the action bar
ActionBar actionBar = getSupportActionBar();

// Customize the back button
actionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_24);

// Showing the back button in action bar
actionBar.setDisplayHomeAsUpEnabled(true);

What I am not certain now is that I wish to add a TextView in the same actionbar (towards the end of the actionbar) but I am not clear on how I can do so?

also I would need to add a onClickListened on the TextView as I would like for it to perform an action when user click on it.

Can anyone please let me know how I can achieve that?

actionbar.setTitle will change the title. Using a Toolbar will be better if you want to customize it. can you give a more detailed example on what you are trying to achieve.

If I'm not wrong you are trying to add a TextView in your ActionBar which is not possible. The alternate approach is to use a Toolbar.

Inside your Toolbar add a ViewGroup (eg LinearLayout, RelativeLayout, etc) and define your TextView inside that ViewGroup.

Code Example

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/your_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </androidx.appcompat.widget.Toolbar>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM