随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)、QQ技术交流群(183198395)。
拖动条通过滑块的位置来标识数值,而且拖动条允许用户拖动滑条来改变值,因此,它常用于对系统的某种数值进行调节,如音量等。android:thumb:指定一个Drawable对象,该对象将作为自定义滑块。星级评分条与拖动条十分相似,它们甚至有相同的父类:AbsSeekBar。区别在于RatingBar通过星星来表示进度。下面列出RatingBar所支持的常见XML属性:
下面通过一个实例来演示它们的使用,实现动态改变图片的透明度。
Activity:
package com.lovo;
import android.app.Activity;
import android.os.Bundle;
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获得ImageView实例
final ImageView image1 = (ImageView) findViewById(R.id.image1);
final ImageView image2 = (ImageView) findViewById(R.id.image2);
// 获得拖动条SeekBar实例
SeekBar seekBar = (SeekBar) findViewById(R.id.seekbar);
// 获得星级评分条RatingBar实例
RatingBar rateingBar = (RatingBar) findViewById(R.id.rating);
// 为SeekBar注册监听事件
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// 动态改变图片1的透明度
image1.setAlpha(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// 为RatingBar注册监听事件
rateingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// 动态改变图片2的透明度,其中255是星级评分条的最大值,5个星就代表最大值255
image2.setAlpha((int) (rating * 255 / 5));
}
});
}
}
布局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:layout_width="wrap_content"
android:layout_height="100dp"
android:id="@+id/image1"
android:src="@drawable/image1"/>
<SeekBar android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="255"
android:id="@+id/seekbar"/>
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:max="255"
android:progress="255"
android:stepSize="0.5"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:id="@+id/image2"
android:src="@drawable/image2"/>
</LinearLayout>
附上图片效果: