欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-04-12 19:36:31
TabHost+TabWidget+FragmentLayout1.1 主布局main_layout 自带布局

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实现选项卡

本文地址:https://blog.csdn.net/qq_33766045/article/details/107591399