選顯卡:類似於QQ VX等主頁面下方的幾個小格子,就是這個東西
↓
需要TabHost | TabWidget | FrameLayout三個組件
-
TabHost => id值固定使用@android:id/tabhost
-
Tabwidget => id值固定使用@android:id/tabs
-
FrameLayout => id值固定使用@android:id/tabcontent
<?xml version="1.0" encoding="utf-8"?>
<!-- 界面整體,id的值不可變 -->
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 選項標籤欄 id值不可變-->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<!-- 具體的內容頁-->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@android:id/tabs">
<!--第一個頁面佈局-->
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是第一個頁面"
android:textSize="25sp"/>
</LinearLayout>
<!--第二個頁面佈局-->
<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是第二個頁面"
android:textSize="25sp"/>
</LinearLayout>
</FrameLayout>
</RelativeLayout>
</TabHost>
獲取TabHost組件之後進行操作
-
啓動 setup
-
創建TabSpec頁面 => 一個選項卡+一個頁面
-
向TabHost添加TabSpec頁面 => addTab方法
package net.onest.tabhostch0203;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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 = findViewById(android.R.id.tabhost);
tabHost.setup();
TabHost.TabSpec tab1 = tabHost.newTabSpec("message_tab")
.setIndicator("短信")
.setContent(R.id.tab1);
TabHost.TabSpec tab2 = tabHost.newTabSpec("contact_tab")
.setIndicator("聯繫人")
.setContent(R.id.tab2);
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
Log.e("切換選項",tabId);
}
});
}
}