Android : how to set Text in TabLayout items by Programming

การเปลี่ยนชื่อ Tab items ที่สร้างอยู่ภายใน TabLayout แบบพื้นฐานทั่วไปคือ ไปกำหนดใน XML layout ที่สร้างไว้ ดังตัวอย่าง

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorColor="@color/white"
    app:tabIndicatorHeight="4dp">

    <com.google.android.material.tabs.TabItem
        android:id="@+id/tabItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tab-name1" />

    <com.google.android.material.tabs.TabItem
        android:id="@+id/tabItem2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tab-name2" />

    <com.google.android.material.tabs.TabItem
        android:id="@+id/tabItem3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tab-name3" />

</com.google.android.material.tabs.TabLayout>

คราวนี้ถ้าเราต้องการจะเปลี่ยนชื่อด้วยการ Programming ใน Java เราสามารถทำได้ดังนี้

TabLayout tabLayout = findViewById(R.id.tabs_main);
TabLayout.Tab tab_item1 = tabLayout.getTabAt(0);
TabLayout.Tab tab_item2 = tabLayout.getTabAt(1);
TabLayout.Tab tab_item3 = tabLayout.getTabAt(2);

tab_item1.setText("new-tab-name1");
tab_item2.setText("new-tab-name2");
tab_item3.setText("new-tab-name3");

เท่านี้เราก็สามารถโปรแกรมใส่เงื่อนไขในการเปลี่ยนชื่อตามที่เราต้องการได้แล้ว

You may also like...