Android 拖动条(SeekBar)实例 附完整demo项目代码
1、拖动条的事件
实现SeekBar.OnSeekBarChangeListener接口。需要监听三个事件:
数值改变(onProgressChanged)
开始拖动(onStartTrackingTouch)
停止拖动(onStopTrackingTouch)
onStartTrackingTouch开始拖动时触发,与onProgressChanged区别是停止拖动前只触发一次
而onProgressChanged只要在拖动,就会重复触发。
2、拖动条的主要属性和方法
setMax
设置拖动条的数值
setProgress
设置拖动条当前的数值
setSeconddaryProgress
设置第二拖动条的数值,即当前拖动条推荐的数值
代码:
package com.zdztools.seekbartest; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; public class MainActivity extends Activity { protected static final String TAG = "MainActivity"; private SeekBar seek; private TextView myTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTextView = (TextView) findViewById(R.id.myTextView); seek = (SeekBar) findViewById(R.id.mySeekBar); //初始化 seek.setProgress(60); seek.setOnSeekBarChangeListener(seekListener); myTextView.setText("当前值 为: -" + 60); } private OnSeekBarChangeListener seekListener = new OnSeekBarChangeListener(){ @Override public void onStopTrackingTouch(SeekBar seekBar) { Log.i(TAG,"onStopTrackingTouch"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { Log.i(TAG,"onStartTrackingTouch"); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Log.i(TAG,"onProgressChanged"); myTextView.setText("当前值 为: -" + progress); } }; }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/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" > <TextView android: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" /> <SeekBar android:id="@+id/mySeekBar" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
运行效果图:
完整项目实例代码:SeekBarTest.zip