Android 控件 - SeekBar

SeekBar 拖动条 常见于音视频播放器的进度或者音量控制。

基本使用

1. XML 属性

属性 注释
max 滑动条的最大值(默认为 100)
progress 滑动条的默认值(默认为 0)
secondaryProgress 二级滑动条的进度
thumb 滑块的 drawable

2. 事件处理

SeekBar.OnSeekBarChangeListener 提供了三个需重写的方法:

方法 注释
onProgressChanged 进度发生改变时触发
onStartTrackingTouch 按住 SeekBar 时触发
onStopTrackingTouch 放开 SeekBar 时触发

示例代码

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="1919810"
android:progress="114514"
android:padding="15dp" />

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingVertical="15dp"
android:text="114514 / 1919810" />

</LinearLayout>

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SeekBar seekBar = findViewById(R.id.seekBar);
final TextView tv = findViewById(R.id.textView);

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tv.setText(progress + " / " + seekBar.getMax());
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this, "按住了 SeekBar", Toast.LENGTH_SHORT).show();
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this, "放开了 SeekBar", Toast.LENGTH_SHORT).show();
}
});
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×