通常窗口标题是在AndroidManifest.xml中通过android:label="@string/app_name"或setText方法来设置,如果我们想在窗体标题中放置自定义标题如:图片或按钮等之类的组件,就无从下手了。
res/layout/main.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="fill_parent"
android:orientation="vertical" ><TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" /></LinearLayout>
res/layout/title.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="horizontal"><TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff000000"
android:text="这是定制的title"
/><Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加"
android:onClick="add"/></LinearLayout>
MainActivity.java
package org.com.customtitle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;public class MainActivity extends Activity {
/** 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);
}
public void add(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "执行了add方法", Toast.LENGTH_LONG).show();
}
}
res/values/style.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources><style name="myTheme" parent="android:Theme">
<item name="android:windowContentOverlay">@drawable/nonecolor</item>
<item name="android:windowTitleSize">44dp</item>
<item name="android:windowTitleBackgroundStyle">@style/mytitlebackground</item>
</style><drawable name="nonecolor">#00000000</drawable>
<style name="mytitlebackground">
<item name="android:background">@drawable/rectangle</item>
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.com.customtitle"
android:versionCode="1"
android:versionName="1.0" ><uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" android:theme="@style/myTheme" >
<activity android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application></manifest>
结果: