activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="10dp" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="改变图片透明度" android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- android:numStars 多少颗星 android:rating 默认多少颗星 android:stepSize 最小变动0.5颗星 --> <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="4" android:rating="4" android:stepSize="0.5" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/pic1" /> </LinearLayout>
MainActivity.java
public class MainActivity extends Activity{ RatingBar ratingBar1; ImageView imageView1; Handler handler=new Handler(){ public void handleMessage(Message msg) { if(msg.what==123){ float alpha =msg.getData().getFloat("alpha"); imageView1.setImageAlpha((int)alpha); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView1=(ImageView)findViewById(R.id.imageView1); ratingBar1=(RatingBar)findViewById(R.id.ratingBar1); ratingBar1.setOnRatingBarChangeListener(new OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { Message msg=new Message(); msg.what=123; Bundle data=new Bundle(); //rating:当前是几颗星 //getNumStars:总共多少颗星 //rating*255/ratingBar1.getNumStars():在255中的位置 data.putFloat("alpha", rating*255/ratingBar1.getNumStars()); msg.setData(data); handler.sendMessage(msg); } }); } }