Activity中代碼在onCreate方法中java
super.onCreate(savedInstanceState); setContentView(R.layout.activity_no_action_bar); //自繪ActionBar ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.MATCH_PARENT,Gravity.CENTER); View viewTitleBar = getLayoutInflater().inflate(R.layout.custom_action_bar, null); getActionBar().setCustomView(viewTitleBar, lp); getActionBar().setDisplayShowHomeEnabled(false); getActionBar().setDisplayShowTitleEnabled(false); getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getActionBar().setDisplayShowCustomEnabled(true);
佈局xml文件android
<?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="fill_parent" android:orientation="horizontal" android:layout_gravity="bottom" android:background="@drawable/ab_texture_tile_androidtest" android:layout_margin="0dp" android:padding="0dp" > <ImageButton android:id="@+id/imageButton1" android:layout_width="44dp" android:layout_height="fill_parent" android:layout_margin="0dp" android:background="@drawable/ab_background_textured_androidtest" android:src="@android:drawable/btn_star" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="44dp" android:text="標題更長的標題" android:gravity="center" android:textSize="16sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:gravity="end" > <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="Button" android:background="@drawable/ab_background_textured_androidtest" /> </LinearLayout> </LinearLayout>
這才應該算是真正的自繪ActionBar,用到了自定義的佈局。佈局