以下的activity是選項卡式的應用程序。
public class TabbedActivity extends TabActivity {
/** activity第一次創建時調用 */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbedactivity);
TabHost tabHost = getTabHost();
TabSpec photospec = tabHost.newTabSpec("RP");
// 為Tab設置Title和Icon
photospec.setIndicator("RP", getResources().getDrawable(R.drawable.tabrp));
Intent photosIntent = new Intent(this, RP.class);
photospec.setContent(photosIntent);
// Tab for Songs
TabSpec songspec = tabHost.newTabSpec("MP");
songspec.setIndicator("MP", getResources().getDrawable(R.drawable.tabmp));
Intent songsIntent = new Intent(this, MP.class);
songspec.setContent(songsIntent);
tabHost.addTab(photospec);
tabHost.addTab(songspec);
}
}
定義的tabbedactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
</TabHost>
我添加了tabmp.xml和tabrp.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/white"/>
<item android:state_focused="true" android:drawable="@color/white"/>
<item android:state_pressed="true" android:drawable="@color/white"/>
<item android:drawable="@color/gray" />
</selector>
我在color.xml
中定義了顏色屬性。程序也能很好的執行,但是當tabs有動作時,它的顏色是默認的黑色,沒有動作時,是灰色的,當點擊時是藍色的。這樣看來tabmp.xml和tabrp.xml
是不能正常運行的,如何改這裡的代碼呢?
1.如果你創建了tab
tabHost.getTabWidget().getChildAt(THE_CHILDS_POSITION_IN_THE_HOST).setBackgroundResource(R.drawable.tabmp.xml);
2.為tab創建一個自定義的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabsLayout" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@drawable/tab_bg_selector"
android:padding="10dp" android:gravity="center" android:orientation="vertical">
<TextView android:id="@+id/tabsText" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Title"
android:textSize="15dp" android:textColor="@drawable/tab_text_selector"
android:textStyle="bold" />
</LinearLayout>
然後創建你的tab:
View tabview = LayoutInflator.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView)view.findViewById(R.id.tabsText);
tv.setText(TEXT);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(i);
tabHost.addTab(setContent);