一、XML静态设置TabItem:
<com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="409dp" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:layout_marginEnd="32dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="北京" /> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上海" /> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="广州" /> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="深圳" /> </com.google.android.material.tabs.TabLayout>
MainActivity.java添加代码:
tabLayout1 = findViewById(R.id.tabLayout);
textView1 = findViewById(R.id.textView);
tabLayout1.getTabAt(0).select();
textView1.setText("北京");
tabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tabLayout1.getSelectedTabPosition();
switch (position){
case 0:
textView1.setText("北京");
break;
case 1:
textView1.setText("上海");
break;
case 2:
textView1.setText("广州");
break;
case 3:
textView1.setText("深圳");
break;
default:
break;
}
}
运行效果:
二、动态设置TabItem:
1)、xml代码:
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout2"
android:layout_width="409dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.google.android.material.tabs.TabLayout>
java部分代码: tabLayout11 = findViewById(R.id.tabLayout2); imageView11 = findViewById(R.id.imageView); tabLayout11.addTab(tabLayout11.newTab().setText("杭州")); tabLayout11.addTab(tabLayout11.newTab().setText("苏州")); tabLayout11.addTab(tabLayout11.newTab().setText("武汉")); tabLayout11.addTab(tabLayout11.newTab().setText("重庆"));
运行效果:
2)、java部分代码:
tabLayout21 = findViewById(R.id.tabLayout3);
textView21 = findViewById(R.id.textView4);
for (int i = 0; i < 18; i++) {
list.add("tab" + i +"");
tabLayout21.addTab(tabLayout21.newTab().setText(list.get(i)));
}
tabLayout21.getTabAt(0).select();
textView21.setText(list.get(0));
tabLayout21.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tabLayout21.getSelectedTabPosition();
textView21.setText(list.get(position));
}
运行效果:
三、完整工程: