代码改变世界

自定义标题栏

2010-12-03 10:25  RayLee  阅读(609)  评论(0编辑  收藏  举报

应用程序默认的标题栏仅仅是文字显示,过于单调。Android允许自定义标题栏以显示更丰富的内容。下面是实现的步骤:

自定义标题栏布局

创建window_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="fill_parent"
  android:orientation="horizontal"
  >
  
	<TextView android:id="@+id/title" 
			android:layout_width="wrap_content"
			android:layout_height="fill_parent"
			android:layout_weight="1.0"
			android:text="This is custom title"
			style="?android:attr/windowTitleStyle" />
			
	<ProgressBar android:id="@+id/progressBar" 
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="center"
			style="?android:attr/progressBarStyleSmallTitle" />
</LinearLayout>

值得注意的是,对TextView需要应用style="?android:attr/windowTitleStyle",否则就是普通的字体显示,而不是放大的高亮的标题栏字体显示。

应用自定义布局

创建好自定义布局后,在Activity初始化时应用该布局

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.window_title);
	}
}

来看看最终的效果图吧

custom_title