Android修改Toolbar标题:使用自定义文本替换应用名称
Hey there! Your approach to adding a custom title via a TextView inside the Toolbar is spot-on—here's how to make sure it fully replaces the default app name without any conflicts:
1. Your XML Layout is Already Correct
First off, your existing XML properly defines a Toolbar with a embedded custom title TextView. Let's highlight it for clarity:
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorPrimary" android:elevation="20dp"> <TextView android:id="@+id/toolbartitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="my toolbar"/> </android.support.v7.widget.Toolbar>
This setup gives you full control over the title's styling (font, color, size, position) which is way more flexible than relying on the default Toolbar title.
2. Disable the Default Title in Your Activity Code
The key step to hide the default app name is turning off the system's built-in title view. Add this code to your Activity's onCreate method:
Kotlin:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.your_layout_file_name) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) // Hide the default app name title supportActionBar?.setDisplayShowTitleEnabled(false) }
Java:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout_file_name); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Hide the default app name title if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); } }
3. Optional: Polish Your Custom Title
If you want to match the default ActionBar title's style (or make it stand out), add these attributes to your TextView:
android:textSize="?attr/textAppearanceLarge"to use the system's default large text sizeandroid:textColor="@color/your_preferred_color"to set a custom text colorandroid:layout_marginStart="16dp"to align it with standard ActionBar padding (if needed)
Why This Works
By embedding your own TextView inside the Toolbar, you bypass the system's default title view. Disabling displayShowTitleEnabled ensures the app name doesn't render alongside your custom text, leaving your "my toolbar" title as the only visible one.
内容的提问来源于stack exchange,提问作者Ali Khaki

