Android自定义标题栏

项目中用到标题栏,发现安卓提供的actionbar无法将标题居中显示,另外标题栏的颜色需要自定义,所以需要使用自定义标题栏  。

新建工程MyTitle,不用修改main.xml文件,在/res/layout目录下新建布局文件title.xml,在里面添加一个TextView和一个Button,完整的title.xml文件如下:

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="match_parent"
5 android:orientation="horizontal"
6 >
7
8 <TextView
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 android:text="这是定制的标题栏"
12 android:textStyle="bold"
13 android:textColor="#FFFF0000"
14 />
15
16 <Button
17 android:id="@+id/button"
18 android:layout_width="wrap_content"
19 android:layout_height="wrap_content"
20 android:text="点我"
21 />
22
23 </LinearLayout>
复制代码

在/res/values目录下新建titlestyle.xml文件,在里面定义两个style,一个用来修改标题栏的大小,一个用来修改标题栏的背景颜色,如下:

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
2
3 <resources>
4
5 <style name="TitleBackgroundColor">
6 <item name="android:background">#FF0000FF</item>
7 </style>
8
9 <style name="titlestyle" parent="android:Theme" >
10 <item name="android:windowTitleSize">40dip</item>
11 <item name="android:windowTitleBackgroundStyle">@style/TitleBackgroundColor</item>
12 </style>
13
14 </resources>
复制代码

修改AndroidManifest.xml文件,在application标签下添加一行:

android:theme="@style/titlestyle"

最后,修改MyTitleActivity.java文件,设置使用自定义的标题栏,实现Button按钮的监听,如下:

复制代码
 1 package com.nan.title;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.view.Window;
7 import android.widget.Button;
8 import android.widget.Toast;
9
10 public class MyTitleActivity extends Activity
11 {
12 private Button mButton = null;
13
14 /** Called when the activity is first created. */
15 @Override
16 public void onCreate(Bundle savedInstanceState)
17 {
18 super.onCreate(savedInstanceState);
19 //使用自定义标题栏
20 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
21 setContentView(R.layout.main);
22 //使用布局文件来定义标题栏
23 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
24
25 mButton = (Button)this.findViewById(R.id.button);
26 //按钮监听
27 mButton.setOnClickListener(new View.OnClickListener()
28 {
29
30 @Override
31 public void onClick(View v)
32 {
33 // TODO Auto-generated method stub
34 displayToast("Clicked!");
35 }
36 });
37
38 }
39
40 //显示Toast函数
41 private void displayToast(String s)
42 {
43 Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
44 }
45
46 }
复制代码

注意上面程序的第20~23行的顺序不能调乱。

运行该程序:

点击一下“点我”按钮:

【转】 http://www.cnblogs.com/lknlfy/archive/2012/03/08/2385724.html

原文地址:https://www.cnblogs.com/lucky-star-star/p/3855480.html