viewpage2简单实现tablayout

该博客介绍了如何在Android应用中使用ViewPager2实现懒加载模式。作者通过创建TabLayoutActivity展示了一个实例,包括设置TabLayout和ViewPager2的适配器,并使用TabLayoutMediator进行联动。此外,还展示了TestFragment的实现,用于在每个tab中显示内容。博客重点在于利用ViewPager2的特性进行高效的内容加载。
摘要由CSDN通过智能技术生成

viewpage2本身自带了懒加载模式,十分人性化。

class TabLayoutActivity : AppCompatActivity() {
    private lateinit var mPagerAdapter: TabPagerAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tablayout)
        mPagerAdapter = TabPagerAdapter(this)
        initTab()

//        initOther()
    }

    private fun initOther(){
        val joinStr1 = arrayOf("a","b","c","d").joinToString(
            separator = "",prefix = "前缀",postfix = "后缀",limit = 3,truncated = "····"
        ).apply {
            print(this)
        }
    }

    private fun initTab() {
        val titles = arrayListOf(
            "精选",
            "体育",
            "巴萨",
            "购物",
            "明星",
            "视频",
            "健康",
            "励志",
            "图文",
            "本地",
            "动漫",
            "搞笑",
            "舞蹈",
            "其他"
        )

        val fragments = ArrayList<Fragment>()
        titles.indices.map { i->
            fragments.add(TestFragment())
        }

        mPagerAdapter.setNewFragments(fragments)

        viewpager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        viewpager.adapter = mPagerAdapter

        TabLayoutMediator(
            tabs, viewpager,
            TabLayoutMediator.TabConfigurationStrategy { tab, position -> tab.text = titles[position] }
        ).attach()


        viewpager.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){

        })


    }
class TestFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_item_one, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        tv_item.text = javaClass.name
        tv_item.background = ContextCompat.getDrawable(requireContext(), R.mipmap.bianpao)
    }
}

class TabPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {

    private val mFragmentList = ArrayList<Fragment>()

    fun setNewFragments(data: ArrayList<Fragment>) {
        if (data.isNotEmpty()) {
            mFragmentList.clear()
            mFragmentList.addAll(data)
            notifyDataSetChanged()
        }
    }

    fun removeFragment(position: Int) {
        if (mFragmentList.size > position) {
            mFragmentList.remove(mFragmentList[position])
            notifyDataSetChanged()
        }
    }

    override fun getItemCount(): Int {
        return mFragmentList.size
    }

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

}

好的,下面是使用ViewPager和TabLayout实现滑动效果的步骤: 1.在布局文件中添加ViewPager和TabLayout组件 ```xml <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" app:tabMode="scrollable" app:tabTextColor="@android:color/white" app:tabSelectedTextColor="@android:color/white" app:tabIndicatorColor="@android:color/white" app:tabIndicatorHeight="3dp" /> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 2.在Java代码中初始化ViewPager和TabLayout组件 ```java ViewPager viewPager = findViewById(R.id.viewPager); TabLayout tabLayout = findViewById(R.id.tabLayout); MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); ``` 3.实现FragmentPagerAdapter类,用于管理ViewPager中的Fragment ```java public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private String[] titles = {"Tab 1", "Tab 2", "Tab 3"}; public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return new Fragment1(); case 1: return new Fragment2(); case 2: return new Fragment3(); default: return null; } } @Override public int getCount() { return titles.length; } @Nullable @Override public CharSequence getPageTitle(int position) { return titles[position]; } } ``` 4.实现三个Fragment类,用于显示在ViewPager中的内容 ```java public class Fragment1 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1_layout, container, false); return view; } } public class Fragment2 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment2_layout, container, false); return view; } } public class Fragment3 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment3_layout, container, false); return view; } } ``` 5.创建三个布局文件fragment1_layout.xml、fragment2_layout.xml、fragment3_layout.xml,用于显示在ViewPager中的内容 ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:text="Fragment 1" android:textSize="30sp" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:text="Fragment 2" android:textSize="30sp" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:text="Fragment 3" android:textSize="30sp" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` 以上就是使用ViewPager和TabLayout实现滑动效果的步骤,希望对你有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值