PS:看了9年的小说,自己开始动手写了一本,请各位猿们动动手指,点击下,有起点账号的可以收藏下!!《武意长存》
在Android中, Activity标题栏默认只能显示一段文字,而且不能改变它的布局、颜色、标题栏的高度等。但单调的文字显示并不能满足开发者的需求,因此只能使用自定义的标题栏。
自定义标题栏有两种方法:
方法一、在Activity的onCreate方法中添加以下代码
//注意:以下代码的顺序不能改变 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); //第二个参数是标题栏的布局
以上代码在4.0之后会报错,要想在4.0之后的版本继续使用以上代码,则必须在manifest中更改Activity的主题(4.0之后默认的主题是android:Theme.Light)
<activity android:name="com.blank.customtitle.MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme" >
虽然上面的代码可以在标题栏中加入一些控件,但是仍然不能改变标题栏的高度、背景色,要想达到这个目的,只能使用自定义的主题。
在/res/values/styles.xml中添加定义的主题
<style name="CustomWindowTitleBackground">
<item name="android:background">#00ffff</item>
</style>
<style name="CustomTitle" parent="android:Theme">
<!—默认的title高度是25dp-->
<item name="android:windowTitleSize">60dp</item>
<item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
</style>
<activity
android:name="com.blank.customtitle.MainActivity"
android:label="@string/app_name"
android:theme="@style/CustomTitle" >
方法二、隐藏掉默认的标题栏,然后再Activity布局文件中添加自定义的标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
/res/layout/activity_main. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!—- 自定义title的布局 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/title"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="自定义title"
android:textSize="22sp"
android:textColor="#ffffff"/>
</RelativeLayout>
</LinearLayout>
上面的做法是在代码中实现的,也可以在manifest.xml文件中进行配置
<activity android:name=".MainActivity" android:theme=" @android:style/Theme.Light.NoTitleBar "></activity>