1.首先建立一个标题布局文件title.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#FF0000"
android:text="自定义标题" />
<Button
android:layout_marginRight="1dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加"
android:onClick="add"/>
</LinearLayout>
2.在styles.xml文件中创建一个style继承并覆盖系统的属性
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 继承并覆盖父类的属性(系统) -->
<style name="salyfanTheme" parent="android:Theme">
<!-- 设置前景颜色 -->
<item name="android:windowContentOverlay">@drawable/nonecolor</item>
<item name="android:windowTitleSize">44dp</item>
<!-- 设置背景颜色 -->
<item name="android:windowTitleBackgroundStyle">@style/salybg</item>
</style>
<!-- 背景风格 -->
<style name="salybg">
<item name="android:background">@drawable/rectangle</item>
</style>
</resources>
3.在strings.xml文件中添加前景颜色
<resources>
<string name="app_name">TitleDemo</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">自定义标题</string>
<drawable name="nonecolor">#00000000</drawable>
</resources>
4.在manifest.xml文件中修改系统的theme
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.saly.titledemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/salyfanTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
5.在activity里添加设置代码
package com.saly.titledemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置窗口的特性为自定义标题
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
//获取窗口对象,设置特征值和界面文件
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.title);
}
//为title里的按钮添加实践
public void add(View v){
Toast.makeText(this, "添加",1).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
6.显示效果