卡片布局—TabHost
使用TabHost需要注意的就是:1.活动需要继承TabHost,2.TabHost布局中id需要使用系统自带的
布局文件如下:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabhost" > <!-- 注意使用自带的id,这样在活动中通过getTabHost方法才能找到 --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- 卡片的 小部件 代表整个卡片的项--> <TabWidget android:id="@android:id/tabs" android:layout_height="wrap_content" android:layout_width="match_parent"/> <!-- 帧布局显示内容 --> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab1"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff0000" android:text="第一个卡片" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab2"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00" android:text="第二个卡片" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost>
活动代码如下:
public class MainActivity extends TabActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost tabHost=getTabHost();//为整个TabHost布局文件 //Intent intent=new Intent(this,Tab1.class); //生成一个TabSpec对象,这个对象代表一个页 TabSpec tabSpec = tabHost.newTabSpec("监听器方法的id"); //为该页设置指示器(卡片的标题) tabSpec.setIndicator("卡片1", getResources().getDrawable(android.R.drawable.sym_action_chat)); //为该页设置显示的内容 tabSpec.setContent(R.id.tab1); //将该页添加到tabHost当中 tabHost.addTab(tabSpec); //第二个卡片的设置 TabSpec tabSpec2 = tabHost.newTabSpec("tab2"); tabSpec2.setIndicator("卡片2"); tabSpec2.setContent(R.id.tab2);//可设置为布局文件,也可以为Intent对象 tabHost.addTab(tabSpec2); //设置监听器 tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { if(tabId.equals("监听器方法的id")){ System.out.println("你选择的是卡片1"); }else if(tabId.equals("tab2")){ System.out.println("你选择的是卡片2"); } } }); } }
效果如下: