HorizontalScrollView将子View布局居中

HorizontalScrollView 只能拥有一个子View,所以,使用HorizontalScrollView 会配合布局使用,通常使用LinearLayout,然后LinearLayout内置多个子View。

我在使用过程中,如果使用默认情况,会出现添加的布局从左到右挨个排列。
如果设置LinearLayout的
android:layout_gravity=”center_horizontal”,
当子View不满一屏时是居中分布,当超过一屏时,会发现左侧的第一个View显示不全,所以这个属性设置存在问题。

我使用下列方法解决这个问题,HorizontalScrollView宽为wrap_content,不为match_parent。并将HorizontalScrollView设置为布局水平居中,添加android:gravity=”center_horizontal”属性,让子布局在HorizontalScrollView中也居中。

<HorizontalScrollView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintLeft_toLeftOf="parent"
     android:gravity="center_horizontal">

    <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">

        <View
            .../>

        <View
            .../>

    </LinearLayout>
</HorizontalScrollView>

这样就可以把View居中显示了,也不会因为布局超过一屏而出现被遮挡现象。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以通过两种方式实现这个功能: 1. 使用 `TabLayout` 的 `addOnTabSelectedListener` 方法,监听标签选中事件,在选中标签后,使用 `HorizontalScrollView` 的 `smoothScrollTo()` 方法将选中的标签滚动到居中位置。 ```java TabLayout tabLayout = findViewById(R.id.tabLayout); HorizontalScrollView scrollView = findViewById(R.id.scrollView); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { // 获取选中标签的索引 int position = tab.getPosition(); // 获取标签的宽度 int tabWidth = tabLayout.getTabAt(position).getCustomView().getWidth(); // 获取屏幕宽度 int screenWidth = getResources().getDisplayMetrics().widthPixels; // 计算要滚动的距离,使选中标签居中 int scrollDistance = (tabWidth - screenWidth) / 2; // 滚动到指定位置 scrollView.smoothScrollTo(scrollDistance, 0); } @Override public void onTabUnselected(TabLayout.Tab tab) { // Do nothing } @Override public void onTabReselected(TabLayout.Tab tab) { // Do nothing } }); ``` 2. 自定义 `TabLayout` 的样式,使其支持居中显示选中标签。您可以使用 `TabGravity.CENTER` 属性将标签居中显示。 在 XML 布局文件中,将 `TabLayout` 的 `tabGravity` 属性设置为 `center`: ```xml <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabGravity="center" /> ``` 请注意,第二种方式只是将选中标签居中显示,并不会自动滚动到居中位置。如果您需要在选中标签后进行滚动,仍然需要使用第一种方式中的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值