android控件开发之RatingBar
本博文主要讲述的RatingBar的开发,此控件主要是用做评分,评级中使用,下面我们来看看实例代码:
MainActivity.java:
package com.example.ratingbar;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
public class MainActivity extends Activity {
private RatingBar ratingBar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ratingBar = (RatingBar)findViewById(R.id.myRatingBar);
//绑定RatingBar的监听器
ratingBar.setOnRatingBarChangeListener(new setRatingBarListener());
}
//创建RatingBar的监听器
class setRatingBarListener implements RatingBar.OnRatingBarChangeListener{
//当RatingBar的等级改变时调用此方法
@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
// TODO Auto-generated method stub
System.out.println("RatingBar --->" + rating);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
主布局文件main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<!--numStars表示 多少颗星 stepSize表示每移动一次,前进多少颗星
在宽度设置时,最好采用wrap_content,否则在numstars只能设置分值,而不能设置显示在屏幕中的星的个数
-->
<RatingBar
android:id="@+id/myRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/myText"
android:numStars="4"
android:stepSize="0.5"/>
</RelativeLayout>
显示效果如下:
可以通过设置stepSize,改变每次增加的幅度