一、概述
每一個應用程式預設的標題列(注意與狀態列的區別)只有一行文字(建立工程時的名字),而且顏色、大小等都是固定的,給人的感覺比較單調。但當程式需要美化的時候,那麼修改標題列是就是其中一項內容,雖然Android已經定義了很多樣式資源,但更多時候我們需要使用的是自己定義的樣式。
二、要求
使用自己定義的樣式來修改程式的標題列。
三、實現
建立工程MyTitle,不用修改main.xml檔案,在/res/layout目錄下建立布局檔案title.xml,在裡面添加一個TextView和一個Button,完整的title.xml檔案如下:
| 代碼如下 |
複製代碼 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="這是定製的標題列" android:textStyle="bold" android:textColor="#FFFF0000" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="點我" /> </LinearLayout> |
在/res/values目錄下建立titlestyle.xml檔案,在裡面定義兩個style,一個用來修改標題列的大小,一個用來修改標題列的背景顏色,如下:
| 代碼如下 |
複製代碼 |
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="TitleBackgroundColor"> <item name="android:background">#FF0000FF</item> </style> <style name="titlestyle" parent="android:Theme" > <item name="android:windowTitleSize">40dip</item> <item name="android:windowTitleBackgroundStyle">@style/TitleBackgroundColor</item> </style> </resources> |
修改AndroidManifest.xml檔案,在application標籤下添加一行:
| 代碼如下 |
複製代碼 |
android:theme="@style/titlestyle"
|
最後,修改MyTitleActivity.java檔案,設定使用自訂的標題列,實現Button按鈕的監聽,如下:
| 代碼如下 |
複製代碼 |
package com.nan.title; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.Toast; public class MyTitleActivity extends Activity { private Button mButton = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //使用自訂標題列 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); //使用布局檔案來定義標題列 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title); mButton = (Button)this.findViewById(R.id.button); //按鈕監聽 mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub displayToast("Clicked!"); } }); } //顯示Toast函數 private void displayToast(String s) { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } } |
注意上面程式的第20~23行的順序不能調亂。
運行該程式: