Android开发:定制Activity的标题栏(Titlebar)

peixiaopao 2011-10-13

效果图:

Android开发:定制Activity的标题栏(Titlebar)

定义title栏的自定义布局 title.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
<TextView
  android:id="@+id/left_text"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" 
  android:text="custom_title_left" 
  />
 <TextView
  android:id="@+id/right_text"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentRight="true"
  android:text="custom_title_right"  
  />
</RelativeLayout>

android:layout_width 和 android:layout_height都为wrap_content,因为这里用的相对布局,match_parent会把TextView都挤在一起。

MainAct.java:

package com.wyx.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainAct extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);//必须出现在super.onCreate(savedInstanceState);之后,setContentView(R.layout.main);之前。其意思就是告诉系统,本程序要自己定义Titlebar;
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.title); //则必须出现在setContentView之后,其意思就是告诉系统,自定义的布局是R.layout.titlebar(即,我们前面编写的title.xml)
        final EditText leftTextEdit = (EditText)findViewById(R.id.left_tex_edit);
        final EditText rightTextEdit = (EditText)findViewById(R.id.right_tex_edit);
        final TextView leftText = (TextView)findViewById(R.id.left_text);
        final TextView rightText = (TextView)findViewById(R.id.right_text);
        Button leftbtn = (Button)findViewById(R.id.left_tex_button);
        Button rightbtn = (Button)findViewById(R.id.right_tex_button);
        leftbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				leftText.setText(leftTextEdit.getText().toString());
			}
		});
        
        rightbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				rightText.setText(rightTextEdit.getText().toString());
			}
		});
    }
    
    
}

相关推荐