Simple usage of Seekbar in Android

Seekbar is the drag bar in Android. It is written by inheriting ProgressBar. We often need to use this price control when playing audio and video. Here we briefly introduce the use of this control. Not much nonsense, just go to the code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="当前进度为:50,最大进度为100"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private SeekBar seekbar;
    private TextView tv_progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekbar = findViewById(R.id.seekbar);
        tv_progress = findViewById(R.id.tv_progress);
        //给seekbar设置进度变更监听器
        seekbar.setOnSeekBarChangeListener(this);
        //设置拖动条的当前进度
        seekbar.setProgress(50);
    }

    /**
     * 在进度变更时触发。第三个参数为true表示用户拖动,为false表示代码设置进度
     * @param seekBar
     * @param progress
     * @param fromUser
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        String desc = "当前进度为:"+seekBar.getProgress()+",最大进度为:"+seekBar.getMax();
        tv_progress.setText(desc);
    }

    /**
     * 当开始拖动进度时触发
     * @param seekBar
     */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 在停止拖动进度时触发
     * @param seekBar
     */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}

In this way, we can simply use the progress bar to control and monitor the current progress.

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/115201637