拖動條和進度條很是類似,只是進度條採用顏色填充來代表進度完成的程度,而拖動條則經過滑塊的位置來標識數值——並且拖動條容許用戶拖動滑塊來改變值,所以拖動條一般用於對系統的某種數值進行調節,好比調節音量等。android
因爲拖動條SeekBar繼承了ProgressBar,所以ProgressBar所支持的XML屬性和方法徹底適合用於SeekBar。ide
SeekBar容許用戶改變拖動條的滑塊外觀,改變滑塊外觀經過以下屬性來指定。佈局
爲了讓程序能響應拖動條滑塊位置的改變,程序能夠考慮爲它綁定一個OnSeekBarChangeListener監聽器。字體
下面是經過拖動滑塊改變圖片的透明度實例spa
佈局文件以下。code
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="240dp" android:src="@drawable/lijiang"/> <!--定義一個拖動條,並改變它的滑塊外觀--> <SeekBar android:id="@+id/seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="255" android:progress="255" android:thumb="@mipmap/ic_launcher"/> <!--定義一個拖動條,並改變它的刻度圖標--> <SeekBar android:id="@+id/seekbar2" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="10" android:tickMark="@drawable/tickmark"/> </LinearLayou>
主程序以下。xml
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView image = findViewById(R.id.image); SeekBar seekBar = findViewById(R.id.seekbar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { //動態改變圖片的透明度 image.setImageAlpha(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
上面紅色字體代碼是監聽拖動條上滑塊位置發生改變的關鍵代碼,當滑塊位置發生改變時,ImageView的透明度將變爲該拖動條的當前數值。運行程序如圖。對象
改變拖動條後blog