2种自定义android标题栏titleBar的方法(转)

android默认的标题栏确实有点不敢恭维,有时为了实现个性化的需求需要自定义一套自己的标题栏。下面就来说说两种实现自定义标题栏的方法。
1、利用Activity的requestWindowFeature方法激活window features。再通过window的setFeatureInt方法设定事先定义好的布局文件。
具体代码如下:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        // 这里要主要requestWindowFeature和setContentView先后顺序哦
        setContentView(R.layout.custom_title);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
}


custom_title_1为自定义的标题栏布局文件。
2、通过在manifest文件中设置需要自定义标题栏的Activity的主题。如下:

<activity android:name=".main.About" android:label="@string/about"
android:theme="@style/MyCustom"></activity>
 
<activity android:name=".main.Help" android:label="@string/help"
android:theme="@style/MyCustom"></activity>


在res/values/styles.xml文件中定义好自己的样式

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustom" parent="android:style/Theme.Light">
    <item name="android:windowTitleBackgroundStyle">@style/titleBg</item>
    <item name="android:windowTitleSize">36dp</item>
    <item name="android:windowTitleStyle">@style/titleText</item>
    </style>
 
    <style name="titleBg">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">#63B2D6</item>
        <item name="android:paddingLeft">20dp</item>
    </style>
    <style name="titleText">
        <item name="android:textSize">23sp</item>
        <item name="android:textColor">#424952</item>
    </style>
</resources>


ok,基本就是这样,下面贴一个效果图

android titlebar

猜你喜欢

转载自314270767.iteye.com/blog/1745564