解决TabLayout+viewpager 滑动切换时 布局文件不是从头显示

本文介绍如何在ViewPager的Fragment布局文件中通过设置属性来阻止子视图获取焦点,从而实现更好的滑动体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以在每个viewpager的fragment的布局文件中,  头中添加

android:descendantFocusability="blocksDescendants"





在Android开发中,要实现TabLayout配合ViewPager的上下滑动布局,通常会用到Android的FragmentPagerAdapter和CoordinatorLayout。以下是基本步骤: 1. **引入依赖**: 首先,在您的build.gradle文件中添加`Material Components`库,因为它包含了TabLayoutViewPager的依赖: ```groovy implementation 'com.google.android.material:material:1.x.y' ``` 2. **布局文件**: 创建XML布局文件,包括TabLayoutViewPager。例如: ```xml <?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" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_constraintTop_toTopOf="parent" app:tabGravity="center" app:tabMode="scrollable"/> <androidx.viewpager.widget.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toBottomOf="@id/tab_layout"/> </androidx.constraintlayout.widget.ConstraintLayout> ``` 3. **设置适配器**: 创建FragmentPagerAdapter,并在TabLayout上设置它: ```java // 假设你有三个Fragment List<Fragment> fragments = new ArrayList<>(); fragments.add(new Fragment1()); fragments.add(new Fragment2()); fragments.add(new Fragment3()); TabLayoutAdapter adapter = new TabLayoutAdapter(getSupportFragmentManager(), fragments); tabLayout.setupWithViewPager(viewPager); viewPager.setAdapter(adapter); ``` 4. **自定义适配器**: `TabLayoutAdapter`是一个自定义适配器,继承自`FragmentStatePagerAdapter`(如果需要跨进程),并实现`onCreateViewHolder`和`getItem`方法,用于创建和返回对应的Fragment视图。 5. **响应滑动事件**: TabLayout有自己的滑动监听器,可以监听用户的点击或滑动动作。例如: ```java tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值