android TextView文字跟随seekBar滑动条滑块的位置移动

android有一个很有意思的控件:seekBar,它可以实现手动滑动进度条的进度,也可以自动调整滑块的位置,并能实现各种效果,适用于进度条,选择额度等情况,在这里我们就暂时不多说了,今天我们重点来实现一下与seekBar相关联的一种效果:文字跟随滑块的位置移动。
之前做过这种效果,用的原理是文字的中间位置与滑块中间位置相同,实现了文字随滑块滑动,但也有一些瑕疵:当滑动条宽度为占满屏幕且文字长度大于滑块的宽度时,如果滑块滑到最左边或最右边,文字显示不完全,思来想去,终于让我找到一种精确计算位置而且不会因为滑动条宽度造成文字显示不完全的问题,它的实现原理是:当滑块位于最左端时,文字与滑块左对齐,当滑动到右端时,文字与滑块右对齐,并随着滑块的移动,文字按照滑块的位置和文字长度按比例调整位置,实现平滑滚动。
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、java代码

 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);
                quota = progress;
                int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                tv_quota.measure(spec, spec);
                int quotaWidth = tv_quota.getMeasuredWidth();

                int spec2 = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                tv_quota.measure(spec2, spec2);
                int sbWidth = sb_quota.getMeasuredWidth();
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv_quota.getLayoutParams();
                params.leftMargin = (int) (((double) progress / sb_quota.getMax()) * sbWidth - (double) quotaWidth * progress / sb_quota.getMax());
                tv_quota.setLayoutParams(params);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值