如何将TabLayout固定在ActionBar下方?布局调整技术求助
解决方案:将TabLayout固定在ActionBar下方顶部
首先看你当前的问题:所有布局都嵌套在ScrollView里,导致TabLayout会随着页面滚动而移动,无法固定在顶部。要实现你想要的效果,我们需要调整布局结构,把TabLayout从ScrollView中独立出来,让它固定在ActionBar下方,而Slider和ViewPager放在ScrollView里实现滚动。
修改后的完整布局代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!-- TabLayout 固定在顶部,ActionBar下方 --> <android.support.design.widget.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white" app:tabGravity="fill" app:tabIndicatorColor="#000" app:tabMode="fixed" app:tabSelectedTextColor="@color/colorTextPrimary" app:tabTextColor="@color/colorTextDisable"> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:text="All"/> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Casual"/> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:text="WoMen"/> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:text="New Jeans"/> </android.support.design.widget.TabLayout> <!-- 滚动区域:包含Slider和ViewPager --> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <com.daimajia.slider.library.SliderLayout android:id="@+id/slider" android:layout_width="match_parent" android:layout_height="200dp" /> <!-- 移除了重复的ViewPager,保留正确的那个 --> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </LinearLayout> </ScrollView> </LinearLayout>
关键修改点说明
- 调整布局层级:把TabLayout移到
ScrollView外面,作为外层垂直LinearLayout的第一个子View,这样它就会固定在屏幕顶部(ActionBar下方),不会随滚动移动。 - 删除重复ViewPager:你的原布局里有两个
ViewPager,这是冗余的,保留带有id="@+id/viewpager"的那个即可。 - 优化滚动结构:Slider和ViewPager放在ScrollView内,这样这部分内容可以正常滚动,而TabLayout始终保持在顶部。
效果对比
原来的效果(Slider在TabLayout上方):
修改后的效果(TabLayout固定在顶部):
内容的提问来源于stack exchange,提问作者Ramdas Darwatkar
相关产品推荐
相关产品推荐

