seekBar的的范围有限,有时候设计师要求高度为4dp,此时范围太小,很难滑动成功。因此,我们需要在不改变 UI 的前提下,增加点击和滑动范围。
直接上代码:
public class MainActivity extends AppCompatActivity {
/**
* 增加seekBar滑动范围
*/
private final static int SEEK_SCOPE = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
final SeekBar seekBar = findViewById(R.id.seekbar);
// seekBar的父布局
FrameLayout flParent = findViewById(R.id.fl_parent);
flParent.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Rect seekBarRect = new Rect();
// 获取相对于父view的位置
seekBar.getHitRect(seekBarRect);
// 上下扩大了指定的接收范围
if (event.getY() >= seekBarRect.top - SEEK_SCOPE
&& event.getY() <= seekBarRect.bottom + SEEK_SCOPE
&& event.getX() >= seekBarRect.left
&& event.getX() <= seekBarRect.right) {
// 模拟seekBar事件
MotionEvent obtain = MotionEvent.obtain(event.getDownTime(),
event.getEventTime(), event.getAction(),
event.getX() - seekBarRect.left,
seekBarRect.top + seekBarRect.height() / 2.0F,
event.getMetaState());
return seekBar.onTouchEvent(obtain);
}
return false;
}
});
}
}