android TextView 跟随 seekBar 一起滑动,最简单代码,完美实现,无偏差

本文介绍了一种在Android应用中使SeekBar与TextView同步滑动时避免位置偏移的方法。通过调整TextView的位置,确保其始终准确地显示在SeekBar的Thumb下方,实现了平滑且精确的视觉效果。

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

开发中遇到如题的需求找了一些方法,发现一起移动都会有偏差,于是就自己修改了下代码,可以实现无偏差一起滑动,代码如下:
1.布局代码

<LinearLayout 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"
    android:background="@color/screen_bg"
    android:orientation="vertical">
     <TextView
       android:id="@+id/tv_quota"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textColor="#FF233845"
       android:textSize="15sp"/>
      <SeekBar
          android:id="@+id/sb_quota"
          style="@style/mprogress_horizontal"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:thumb="@mipmap/bulegress_button" />
</LinearLayout>

2.activity代码

 private SeekBar sb_quota;
 private TextView tv_quota;
     tv_quota = (TextView) rootView.findViewById(R.id.tv_quota);
     sb_quota = (SeekBar) rootView.findViewById(R.id.sb_quota);
     sb_quota.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_quota.setText("¥" + progress);
                int quotaWidth = tv_quota.getWidth();
                final Drawable thumb = seekBar.getThumb();
                 //获取thumb的位置
                final Rect bounds = thumb.getBounds();
                //thumb的位置为canvas的相对位置,减去thumb和textview的差值的一半,另外还要加上SeekBar相对屏幕距离
                tv_quota.setX((thumb.getIntrinsicWidth() - quotaWidth) / 2
                        + bounds.left + seekBar.getX());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值