android基础控件(1)TabHost实现选项卡

TabHost+TabWidget+FragmentLayout

1.1 主布局main_layout
<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/tabhost">    自带布局
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TabWidget
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@android:id/tabs"> TabWidget>
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@android:id/tabcontent"/>
    LinearLayout>
TabHost>
1.2 选项卡布局tab1
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/img_01"
android:id="@+id/img1"/>
1.3 选项卡布局tab2
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/img_02"
    android:id="@+id/img2"/>
1.4 选项卡布局tab3
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/img_03"
    android:id="@+id/img3"/>

1.5 选项卡布局tab4
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/img_04"
    android:id="@+id/img4"/>
1.6 主活动代码Main_Acitvity
public class MainActivity extends AppCompatActivity {
    private TabHost tabHost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabHost=findViewById(android.R.id.tabhost);
        tabHost.setup();//初始化控件
        LayoutInflater inflater=LayoutInflater.from(MainActivity.this);
        //加载四个选项卡布局
        inflater.inflate(R.layout.tab1,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab2,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab3,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab4,tabHost.getTabContentView());        
       //为选项卡设置标题
 tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab1").setContent(R.id.img1));    
 tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab2").setContent(R.id.img2));    
 tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Tab3").setContent(R.id.img3));    
 tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator("Tab4").setContent(R.id.img4));
    }
}

效果图展示:
android基础控件(1)TabHost实现选项卡_第1张图片

你可能感兴趣的:(android开发,android,移动开发,tabhost)