从动态android ratingbar获取评级值

时间:2013-03-20 10:06:02

标签: android

由于显示超过5颗星,我动态创建RatingBar并将其分配给警报对话框。这是代码:

rater
    .setCancelable(false)
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //How to get the rating value here

    });
rater.setNegativeButton("Abbrechen", null);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View final layout = inflater.inflate(R.layout.ratinglayout,null);
rater.setView(layout);
//rater.setView(getLayoutInflater().inflate(R.layout.ratinglayout, null));
rater.show();

RatingBar的XML布局是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RatingBar
        android:id="@+id/ratingStars"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="1"
        android:layout_gravity = "center_horizontal"
         />

</LinearLayout>

如何在警告对话框的OK处理程序中获取评级值? 我试过以下内容:

RatingBar rating = (RatingBar) findViewById(R.id.ratingStars);

但是当我这样做时,我得到一个空指针异常警告。因此,问题是如何获得评级值?

2 个答案:

答案 0 :(得分:3)

float rating = ((RatingBar)layout.findViewById(R.id.ratingStars)).getRating();

在你的ok点击处理程序中使用它。请参阅文档here

你正试图走findViewById的{​​{1}}我认为这就是为什么它会返回null。

答案 1 :(得分:2)

 private void showDialog() 
 {

final AlertDialog.Builder popdialog=new AlertDialog.Builder(this);
final RatingBar rating=new RatingBar(this);
popdialog.setIcon(R.drawable.ic_launcher);
popdialog.setTitle("Give us Rattings");
  popdialog.setView(rating);
   rating.setOnRatingBarChangeListener(new OnRatingBarChangeListener() 
{

@Override
public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {

    ratevale=arg1;
}
});