效果展示:
SeekBar简介:
Android的基本UI控件中的拖动条
实现步骤:
activity_seek_bar.xml代码如下:
<?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" tools:context=".SeekBarActivity" android:orientation="vertical" > <SeekBar android:id="@+id/seek_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:max="100" android:thumb="@drawable/seekbar_point" /> <TextView android:id="@+id/tv_seek_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="当前进度为" android:gravity="center" android:textSize="17sp" android:textColor="@color/black" /> </LinearLayout>
SeekBar中的两个属性:
android:thumb=“@drawable/seekbar_point” 自定义滑块的样式
android:max=“100” 滑动条的最大值
SeekBarActivity代码如下:
public class SeekBarActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { private SeekBar seek_bar; private TextView tv_seek_bar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seek_bar); seek_bar = findViewById(R.id.seek_bar); tv_seek_bar = findViewById(R.id.tv_seek_bar); //给拖动条设置拖动变更监听器 seek_bar.setOnSeekBarChangeListener(this); //设置拖动条的当前进度 seek_bar.setProgress(50); } //在进度变更时触发。第三个参数为true表示用户拖动,为false表示代码设置进度 @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { String desc = "当前进度为:" + seekBar.getProgress() + ",最大进度为" + seekBar.getMax(); tv_seek_bar.setText(desc); } //在开始拖动进度时触发 @Override public void onStartTrackingTouch(SeekBar seekBar) { } //在停止拖动进度时触发 @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
通过setOnSeekBarChangeListener(OnSeekBarChangeListener)
的回调方法实现SeekBar
的拖动变更事件。具体注释已经在代码中给出!