Android APP开发TabLayout控制的多样应用

一、XML静态设置TabItem:



    

    

    
    

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;
                }
            }

运行效果:

Android APP开发TabLayout控制的多样应用_第1张图片

二、动态设置TabItem:

1)、xml代码:



    
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("重庆"));

运行效果:

Android APP开发TabLayout控制的多样应用_第2张图片

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));
            }

运行效果:

Android APP开发TabLayout控制的多样应用_第3张图片

三、完整工程:

AndroidAPP开发TabLayout控制的多样应用资源-CSDN文库

你可能感兴趣的:(android,android,gitee)