一、概述
每一個應用程式預設的標題列(注意與狀態列的區別)只有一行文字(建立工程時的名字),而且顏色、大小等都是固定的,給人的感覺比較單調。但當程式需要美化的時候,那麼修改標題列是就是其中一項內容,雖然Android已經定義了很多樣式資源,但更多時候我們需要使用的是自己定義的樣式。
二、要求
使用自己定義的樣式來修改程式的標題列。
三、實現
建立工程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行的順序不能調亂。
運行該程式:
點擊一下“點我”按鈕: