這次介紹的SeekBar類似前面介紹的Progress Bar,但SeekBar有多一個拖曳的滑動桿,SeekBar繼承自ProgressBar,因此SeekBar類別中的很多方法均繼承自ProgressBar。
android:max ="數值" //設定範圍的最大值
android:progress="數值" //設定範圍的目前數值
android:secondaryProgress="數值" //次條SeekBar的數值
android:thumb = "" // 設定SeekBar的外觀
onProgressChanged //進度發生改變時會觸發
onStartTrackingTouch //按住時會觸發
onStopTrackingTouch //停止拖曳時觸發事件
範例:用SeekBar顯示目前的數值,按下和放開時會跳出Toast
xml範例如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="75dp"
android:max="100"
android:progress="0"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:text="目前數值: 0/100" />
</LinearLayout>
MainActivy.java範例如下:
package com.example.itseekbarr;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SeekBar seekBar;
private TextView textView;
private Context Context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = MainActivity.this;
bindViews();
}
private void bindViews() {
seekBar = (SeekBar) findViewById(R.id.seekBar);
textView = (TextView) findViewById(R.id.textView);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText("目前數值:" + progress + " / 100 ");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(Context, "按住SeekBar", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(Context, "放開SeekBar", Toast.LENGTH_SHORT).show();
}
});
}
}
顯示畫面如下: