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() {@Overridepublic 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);}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}});


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部