0

由于显示超过 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();

XML 布局为RatingBar

<?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);

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

4

2 回答 2

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

在你的确定点击处理程序中使用它。请参阅此处的文档

您正在尝试行走findViewByIdActivity我认为这就是它返回 null 的原因。

于 2013-03-20T10:08:42.073 回答
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;
}
});
于 2014-08-07T12:18:56.177 回答