2010年11月18日木曜日

Android カスタムタイトルバーを使う

タイトルバーのレイアウトを XML で定義することができます。

setContentView の前に

 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

で宣言し、setContentView のあとにXMLファイルを

 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

で指定します。


  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.   
  5.     requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);  
  6.           
  7.     setContentView(R.layout.viewer2);  
  8.     
  9.     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);  
  10.   
  11.     // Set up the custom title  
  12.     TextView mTitle;  
  13.     mTitle = (TextView) findViewById(R.id.title_left_text);  
  14.     mTitle.setText(R.string.app_name);  
  15.     mTitle = (TextView) findViewById(R.id.title_right_text);  
  16.     mTitle.setText(R.string.app_version);  
  17. }  



  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     <TextView   
  6.         android:id="@+id/title_left_text"  
  7.         android:layout_alignParentLeft="true"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="match_parent"  
  10.         android:layout_weight="1"  
  11.         android:ellipsize="end"  
  12.         android:singleLine="true"  
  13.         style="?android:attr/windowTitleStyle"  
  14.         android:gravity="center_vertical" >  
  15.         />  
  16.     <TextView   
  17.         android:id="@+id/title_right_text"  
  18.         android:layout_alignParentRight="true"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="match_parent"  
  21.         android:layout_weight="1"   
  22.         android:ellipsize="end"  
  23.         android:singleLine="true"  
  24.         android:textColor="#fff"  
  25.         android:gravity="center_vertical" >  
  26.     />  
  27. </RelativeLayout>  



 android:gravity="center_vertical" > は root view (この場合 RelativeLayout) ではなく、子要素(この場合 TextView)に入れないと、反映されませんでした!

0 件のコメント:

コメントを投稿