2013-03-20 22 views
0

由於顯示超過5顆星,因此我將動態創建RatingBar並將其分配給警報對話框。下面是代碼:從動態Android評分欄獲取評分值

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> 

我怎樣才能得到警告對話框的確定​​處理程序中評定值? 我有特里結構如下:

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

但我得到一個空指針異常的警告當我這樣做。因此,問題是如何獲得評級值?

回答

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

在你的ok點擊處理程序中使用它。請參閱文檔here

您正在嘗試在步行findViewByIdActivity我認爲這就是爲什麼它返回null。

+0

評價者是AlertDialog.Builder如果我嘗試你的代碼,我正在一個findViewById(INT)是未定義的類型AlertDialog.Builder錯誤 – user1107888 2013-03-20 10:28:36

+0

對不起看到編輯的代碼:) – Triode 2013-03-20 10:29:43

+0

它的工作原理,但佈局有被宣佈是最終的,我修改了我自己的代碼以反映它。再次感謝你。 – user1107888 2013-03-20 10:40:29

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