选项卡的使用

时间:2021-11-01 02:13:18

选项卡的创建分为四步:

选项卡的使用

话不多说,下面放代码

第一步:在布局文件中添加TabHost, TabWidget和 TabContent组件

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <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="match_parent"
            android:id="@android:id/tabcontent"></FrameLayout>
    </LinearLayout>


</TabHost>

第二步:编写各标签页的布局文件:

这里我编写了两个布局文件,tab1 和 tab2 :

tab1.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/right">

    <ImageView
        android:src="@drawable/img002"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

tab2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/letf"
    android:orientation="vertical">

    <ImageView
        android:src="@drawable/img05"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

接下来是初始化TabHost组件:

进入Java代码中编写:

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;

public class MainActivity extends AppCompatActivity {

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

        TabHost tabHost = super.findViewById(android.R.id.tabhost);
        tabHost.setup();            //调用setup()方法对TabHost进行初始化

        //接下来就是添加标签页
        LayoutInflater inflater = LayoutInflater.from(this);
        inflater.inflate(R.layout.tab1, tabHost.getTabContentView());
        inflater.inflate(R.layout.tab2, tabHost.getTabContentView());
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("精选表情").setContent(R.id.letf));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("自定义表情").setContent(R.id.right));

    }
}

这样就编写完成了。运行界面如下:

选项卡的使用