天天看點

Android的SeekBar拖動條與RatingBar星級評分條的功能和用法

SeekBar和RatingBar都是ProgressBar的子類,是以他們非常相似,隻是進度條采用顔色填充來表明進度完成的程度,而拖動條和星級評分條則都通過拖動的位置來表示數值。

樣式:

Android的SeekBar拖動條與RatingBar星級評分條的功能和用法

xml檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <ImageView 
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="240px"
        android:src="@drawable/flower"/>
    <SeekBar 
        android:id="@+id/seekbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255"
        android:thumb="@drawable/next"/>
    <RatingBar 
        android:id="@+id/rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="6"
        android:max="255"
        android:progress="255"
        android:stepSize="0.5"
        />
</LinearLayout>      

主程式:

package com.example.seekbar;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {
  ImageView image;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    image = (ImageView) findViewById(R.id.image);
    SeekBar seekBar = (SeekBar) findViewById(R.id.seekbar);
    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
      
      @Override
      public void onStopTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub
        
      }
      
      @Override
      public void onStartTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub
        
      }
      
      @Override
      public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        // TODO Auto-generated method stub
        //image.setAlpha();裡的值為0~255;
        //初始設定最大為255,其實位置為255
        image.setAlpha(arg1);
      }
    });
    RatingBar ratingBar = (RatingBar) findViewById(R.id.rating);
    ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
      
      @Override
      public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {
        // TODO Auto-generated method stub
        //和SeekBar相同,隻不過這裡設定有6顆星,每次隻能改變半個
        image.setAlpha((int)arg1*255/5);
      }
    });
  }
}