因为Android提供的标题栏样式有时不能满足我们的需求,所以有时大家需要自定义的安卓界面标题栏。
下面就写下自定义标题栏的步骤:
一、定义一个样式:
在res->values->styles中增加一个样式:
<style name="CustomWindowTitleBackground">
<item name="android:background">#444</item>
</style>
<style name="CustonTitleBarTheme" parent="android:Theme.Light">
<item name="android:windowTitleSize">50dp</item>
<item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
</style>
此样式指定了标题栏的一些属性,看单词还算比较好理解的。
二、在AndroidManifest.xml中注册界面是指定这个样式:
<activity
android:name="com.xg.shop.user.UserInfoActivity"
android:label="@string/app_name"
android:theme="@style/CustonTitleBarTheme">
</activity>
注册上面红色的部分
三、在代码Activity的onCreate函数中加入以下代码:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_login);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_2);
红色部分的代码,注册代码顺序。
四、在res-layout目录下加入title_bar_2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_back"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="15dp"
android:text="@string/come_back"
android:textColor="#fff"
android:textSize="12px"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_gravity="center|center_vertical"
android:text=""
android:textColor="#fff"
/>
</LinearLayout>
</RelativeLayout>
到此一个自定义标题栏就完成了,这个部分后面大部分的界面都会用到自定义的标题栏。
有啥疑问,加学习QQ群:32961442