Android TabHost选项卡编程

时间:2022-01-21 19:23:48

界面布局文件main_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>

</TabHost>

主活动文件MainActivity.java中:
public class MainActivity extends TabActivity {

private final static String TAG = "System.out";
private TabHost tabHost = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tabHost = getTabHost();
LayoutInflater layoutInflater = LayoutInflater.from(this);
layoutInflater.inflate(R.layout.alarm_layout, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("alarmtab")
.setIndicator("闹钟", getResources().getDrawable(R.drawable.alarm2))
.setContent(R.id.alarm_layout_id));
layoutInflater.inflate(R.layout.contexttual_mode, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("contexttual_mode")
.setIndicator("智能情景模式", getResources().getDrawable(R.drawable.contexttual))
.setContent(R.id.context_mode_id));
layoutInflater.inflate(R.layout.timepiece, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("timepices")
.setIndicator("计时器", getResources().getDrawable(R.drawable._timepices))
.setContent(R.id.timepiece_id));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

其中涉及到的选项卡的界面布局文件是保存在layout文件夹下,并且各个文件的根元素要额外设置一个android:id="@+id/_layout_id",设置这个id在的用处:比如在主活动代码中用它作为函数setContent()的参数来设置该选项卡所对应内容的界面布局方式,如下:
tabHost.addTab(tabHost.newTabSpec("alarmtab")
.setIndicator("闹钟", getResources().getDrawable(R.drawable.alarm2))
.setContent(R.id.alarm_layout_id));


特别注意:

在添加每一个选项卡之前必须要先对相应布局文件调用LayoutInflater.inflate()方法,如下:

layoutInflater.inflate(R.layout.alarm_layout, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("alarmtab")
.setIndicator("闹钟", getResources().getDrawable(R.drawable.alarm2))
.setContent(R.id.alarm_layout_id));