美文网首页
Tablayout的使用

Tablayout的使用

作者: 因为我的心 | 来源:发表于2022-08-02 15:12 被阅读0次

一、前言:

Tablayout继承自HorizontalScrollView,用作页面切换指示器,因使用简便功能强大而广泛使用在App中。

github代码直通车

先上效果图:分别为设置tab属性、去掉指示线、设置指示线长度、设置图标tab、超出屏幕滚动tab

图片.png

二、使用:

1、TabLayout的一些基本属性:

app:tabIndicatorColor :指示线的颜色
app:tabIndicatorHeight :指示线的高度
app:tabSelectedTextColor : tab选中时的字体颜色
app:tabTextColor:tab未被选中时的字体颜色
app:tabMode="scrollable" : 默认是fixed,固定的;scrollable:可滚动的

2、高度设置为0:

给tabIndicatorHeight属性设置0dp,或者给tabSelectedTextColor属性设置透明,就不显示指示线了。

app:tabIndicatorHeight ="0dp"

还可以设置成透明色:

app:tabIndicatorColor="@color/transparent"

3、设置默认图标:

图片.png

still easy,Tablayout自带了setIcon()方法设置图标资源,不过这中效果很别扭,脸被拉长了。不服,就自己造一个啊,造就造!
tabLayout.getTabAt(i).setText(titles[i]).setIcon(pics[i]);

4、自己造tab样式:

图片.png

创建图标和文字布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="48dp"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageview"
        android:layout_gravity="center"
        android:layout_width="24dp"
        android:layout_height="24dp" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="14sp"
        android:layout_marginLeft="8dp"/>
</LinearLayout>

这里是图标居左,那我要改为图标上下左右呢?都自定义view了,你上天都行。

    /**
     * 设置自定义位置图标
     */
    private void setCustomIcon() {

        tabLayout2 = (TabLayout) findViewById(R.id.tablayout2);
        for(int i=0;i<titles.length;i++){
            tabLayout2.addTab(tabLayout2.newTab());
        }

        for(int i=0;i<titles.length;i++){
            tabLayout2.getTabAt(i).setCustomView(makeTabView(i));
        }
    }

    /**
     * 引入布局设置图标和标题
     * @param position
     * @return
     */
    private View makeTabView(int position){
        View tabView = LayoutInflater.from(this).inflate(R.layout.tab_text_icon,null);
        TextView textView = tabView.findViewById(R.id.textview);
        ImageView imageView = tabView.findViewById(R.id.imageview);
        textView.setText(titles[position]);
        imageView.setImageResource(pics[position]);

        return tabView;
    }

5、tab数量太多,超出屏幕,就像今日头条的分类一样,那就挤在一起了啊。不怕,我们有app:tabMode="scrollable" 属性,让Tablayout变得可滚动,可超出屏幕。

图片.png

布局引入:

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabSelectedTextColor="@color/green"
        android:layout_marginTop="20dp"
        app:tabMode="scrollable"
        android:background="@color/white"/>

三、自己写的demo:

图片.png

1、activity

package com.example.day0801

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.day0801.databinding.ActivityMainBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import androidx.databinding.DataBindingUtil
import com.example.day0801.databinding.SearchTabItemBinding


class MainActivity : AppCompatActivity() {
    val tabNames = arrayListOf<String>()
    val childFragments  = arrayListOf<Fragment>()
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        childFragments.add(FirstFragment("第一个页面"))
        childFragments.add(FirstFragment("第二个页面"))
        childFragments.add(FirstFragment("第三个页面"))
        childFragments.add(FirstFragment("第四个页面"))
        childFragments.add(FirstFragment("第五个页面"))


        tabNames.add("测试1")
        tabNames.add("测试2")
        tabNames.add("测试3")
        tabNames.add("测试4")
        tabNames.add("测试5")
        //初始化tab
        initTabButton()
    }


    private fun initTabButton() {

        tabNames.forEachIndexed { _index, it ->
            binding.tablayout.addTab(binding.tablayout.newTab().setText(it))
        }
        binding.viewpager.offscreenPageLimit = 1
        binding.viewpager.adapter = fragmentAdapter



        // 这里是Google的一个坑,注意应先设置监听器,再去添加tab,否则会出现第一次运行不执行onTabSelected方法
        binding.viewpager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
            }
        })

        binding.tablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                updateTabView(tab, true)
                tab?.position?.let {
                    binding.viewpager.setCurrentItem(it, true)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                updateTabView(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        TabLayoutMediator(binding.tablayout, binding.viewpager, false, true) { tab, position ->
            tab.customView = getTabView(tabNames[position])
        }.attach()

        binding.tablayout.getTabAt(0)?.select()
    }

    private fun getTabView(tab: String): View {
        val binding = DataBindingUtil.inflate<SearchTabItemBinding>(layoutInflater, R.layout.search_tab_item, null, true)
        binding.tabName.text = tab
        return binding.root
    }

    private fun updateTabView(tab: TabLayout.Tab?, isSelect: Boolean) {
        Log.d("LUO", "updateTabView: tab=${tab?.position}, isSelectd=$isSelect")
        tab?.let {
            it.customView?.let {
                val binding: SearchTabItemBinding = DataBindingUtil.bind<SearchTabItemBinding>(it)!!
                val color = if (isSelect) {
                    ContextCompat.getColor(this, R.color.teal_200)
                } else {
                    ContextCompat.getColor(this, R.color.ui_color_191c1c)
                }
                binding.tabName.setTextColor(color)
                if (isSelect) {
                    val paint = binding.tabName.paint
                    paint.isFakeBoldText = true
                    binding.tabName.textSize = 16f
                    tab.customView?.findViewById<ImageView>(R.id.iv_indicator)?.apply {
                        visibility = View.VISIBLE
                    }
                } else {
                    val paint = binding.tabName.paint
                    paint.isFakeBoldText = false
                    binding.tabName.textSize = 14f
                    tab.customView?.findViewById<ImageView>(R.id.iv_indicator)?.apply {
                        visibility = View.INVISIBLE
                    }
                }
            }

        }
    }
    /**
     * viewPager adapter
     */
    private val fragmentAdapter: FragmentStateAdapter by lazy {
        object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return tabNames.size
            }

            override fun createFragment(position: Int): Fragment {
                return childFragments[position]
            }
        }
    }
}

2、activity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">


    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tab切换"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="22sp"
        android:textColor="#f00"
        />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:layout_marginTop="10dp"
        android:shadowColor="#f0000000"
        android:shadowDx="0"
        android:shadowDy="2"
        app:tabGravity="fill"
        app:tabIndicatorFullWidth="false"
        app:tabIndicatorHeight="0dp"
        app:tabMinWidth="30dp"
        app:tabMode="scrollable"
        app:tabPaddingEnd="18dp"
        app:tabPaddingStart="12dp"
        app:tabRippleColor="@android:color/transparent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_title"
        />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="2dp"
        app:layout_constraintTop_toBottomOf="@+id/tablayout"
        app:layout_constraintBottom_toBottomOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

3、FirstFragment

class FirstFragment(var tabName:String?="") : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.textviewFirst.text = tabName

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

4、fragment_first

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".FirstFragment">

    <TextView
        android:id="@+id/textview_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_first_fragment"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="100dp"
        />


</androidx.constraintlayout.widget.ConstraintLayout>

相关文章

网友评论

      本文标题:Tablayout的使用

      本文链接:https://www.haomeiwen.com/subject/zwcjwrtx.html