Properties for application specific attributes in Android
I want to center the application title/label in my Android app but I can't find a lot of documentation on how to set that property. I have found a couple of posts saying that I can create a开发者_如何学Python custom title bar and change the theme in my manifest but I just can't help thinking there is a simpler way to just center the title.
In my experience documentation on this isn't great but I figured it out and I'll share. It's actually pretty simple.
Custom centered title bar on your activity:
Add two lines to your activity at the beginning of onCreate()
so it looks like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
...
...
...
}
Now put mytitle.xml in your layout directory. This xml file should look something like this to center your title text:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTitle"
android:textStyle="bold"
android:textSize="15sp"
android:text="My Custom Title Text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:textColor="#FFFFFF"
/>
That's it.
You can change the label of any of your activities with the android:label="@string/app_name"
in your manifest. You can do it in code too. I'm not sure what else you want
精彩评论