标题栏中的返回按钮在实际使用中用的比较多,今天就来讲讲我在项目开发中的使用经历,话不多说,还是直接上源码,上源码是最给力的。

一、 编写自定义类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class CustomTitle { 
  private static Activity mActivity; 
  public static void getCustomTitle(Activity activity, String title) {
   mActivity = activity;
    mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
   mActivity.setContentView(R.layout.custom_title);
    mActivity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
        R.layout.custom_title);    
    TextView textView = (TextView) activity.findViewById(R.id.head_center_text); 
    textView.setText(title); 
   Button titleBackBtn = (Button) activity.findViewById(R.id.TitleBackBtn); 
    titleBackBtn.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 
       Log.d("Title back","key down");
          
        mActivity.finish();
      
    }); 
  }
}

二 、 xml资源,在layout中定义custom_title

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >  
  <Button 
    android:id="@+id/TitleBackBtn" 
    android:layout_width="50dp"   
   android:layout_height="wrap_content"  
    android:gravity="center" 
   android:layout_alignParentRight="true" 
    android:background="@android:drawable/ic_menu_revert"/>     
  <TextView 
    android:id="@+id/head_center_text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
   android:text=""  
    android:textSize="25sp"
    android:textColor="#FFFFFF" 
    /> 
</RelativeLayout>

三 、 在需要调用的activity中调用

1
2
3
4
5
6
7
8
9
10
public class InformationActivity extends Activity{
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub    
super.onCreate(savedInstanceState);         
   CustomTitle.getCustomTitle(this, "个人信息");
    setContentView(R.layout.informationactivity);
  .......................
  }
}

四 、 在res/values/style.xml中添加style定义

1
2
3
4
<style name="MyCustomTheme" parent="android:Theme">    
    <item name="android:windowTitleBackgroundStyle">@style/TitleBarBackground</item> 
    <item name="android:windowTitleSize">50dp</item> 
 </style>

五 、 在AndroidManifest.xml中对InformationActivity添加支持 

1
2
3
android:name="com.xxx.InformationActivity"
 android:theme="@style/MyCustomTheme"
 android:screenOrientation="landscape" />

OK,完成上述几个步骤,就可以了。