Android SeekBar 拖动结束监听:详细代码示例
以下是一个示例代码,演示如何在Android中使用SeekBar监听拖动结束:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private SeekBar seekBar;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = findViewById(R.id.seekBar);
textView = findViewById(R.id.textView);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// 这个方法会在SeekBar的进度改变时被调用
textView.setText('进度:' + progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// 这个方法会在用户开始拖动SeekBar时被调用
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 这个方法会在用户停止拖动SeekBar时被调用
int progress = seekBar.getProgress();
textView.setText('最终进度:' + progress);
}
});
}
}
在上述代码中,我们首先在布局文件中定义了一个SeekBar和一个TextView。然后在Activity中,我们通过findViewById方法获取这两个控件的实例。
接下来,我们通过setOnSeekBarChangeListener方法为SeekBar设置监听器。在监听器的onProgressChanged方法中,我们更新TextView的文本为SeekBar的当前进度。在监听器的onStartTrackingTouch方法中,我们可以执行一些在用户开始拖动SeekBar时需要执行的操作。在监听器的onStopTrackingTouch方法中,我们获取SeekBar的最终进度,并更新TextView的文本为最终进度。
这样,当用户在应用中拖动SeekBar时,我们就可以在TextView中实时显示进度,并在拖动结束时获取最终进度。
原文地址: https://www.cveoy.top/t/topic/qcZC 著作权归作者所有。请勿转载和采集!