Android 拖动条(SeekBar)实例 附完整demo项目代码
1、拖动条的事件
实现SeekBar.OnSeekBarChangeListener接口。需要监听三个事件:
数值改变(onProgressChanged)
开始拖动(onStartTrackingTouch)
停止拖动(onStopTrackingTouch)
onStartTrackingTouch开始拖动时触发,与onProgressChanged区别是停止拖动前只触发一次
而onProgressChanged只要在拖动,就会重复触发。
2、拖动条的主要属性和方法
setMax
设置拖动条的数值
setProgress
设置拖动条当前的数值
setSeconddaryProgress
设置第二拖动条的数值,即当前拖动条推荐的数值
代码:
1 package com.zdztools.seekbartest; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.util.Log; 6 import android.widget.SeekBar; 7 import android.widget.TextView; 8 import android.widget.SeekBar.OnSeekBarChangeListener; 9 10 public class MainActivity extends Activity {11protected static final String TAG = "MainActivity";12private SeekBar seek;13private TextView myTextView;14 15@Override16protected void onCreate(Bundle savedInstanceState) {17 super.onCreate(savedInstanceState);18 setContentView(R.layout.activity_main);19 20 myTextView = (TextView) findViewById(R.id.myTextView);21 seek = (SeekBar) findViewById(R.id.mySeekBar);22 //初始化23 seek.setProgress(60);24 seek.setOnSeekBarChangeListener(seekListener);25 myTextView.setText("当前值 为: -" + 60);26}2728private OnSeekBarChangeListener seekListener = new OnSeekBarChangeListener(){29 @Override30 public void onStopTrackingTouch(SeekBar seekBar) {31 Log.i(TAG,"onStopTrackingTouch");32 }33 34 @Override35 public void onStartTrackingTouch(SeekBar seekBar) {36 Log.i(TAG,"onStartTrackingTouch");37 }38 39 @Override40 public void onProgressChanged(SeekBar seekBar, int progress,41 boolean fromUser) {42 Log.i(TAG,"onProgressChanged");43 myTextView.setText("当前值 为: -" + progress);44 45 }46};47 }
<LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin" ><TextViewandroid:id="@+id/myTextView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dip"android:text=""android:textSize="16sp"android:textStyle="bold" /><SeekBarandroid:id="@+id/mySeekBar"android:layout_width="fill_parent"android:layout_height="wrap_content" /></LinearLayout>
运行效果图:
完整项目实例代码:SeekBarTest.zip
本人另外一篇博客:android三档自定义滑动开关,禁止点击功能的实现,用默认的seekbar组件实现