2

我有一个显示评分栏的警报对话框。

LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
            final View v = rating.inflate(R.layout.rating_layout, null);

            AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);
            adb.setTitle("Rate us!);
            adb.setView(v);
            AlertDialog ratingbar = adb.create();

final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);

当我触发 onclick 监听器时,它显示 NULL POINTER EXCEPTION。第二行错误表示 getNumStars() 行中的错误。之后强制关闭。

adb.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    //this line error. means they cant get the rating value?
final String cleaninput = Integer.toString(cleanbar.getNumStars());

我可以知道任何其他方法来获得评级栏的价值吗?我见过很少有人喜欢 ratingBar.getRating(); ratingBar.getNumStars();

他们都无法工作......即使我将值直接放入int。

final int cleaninput = (int) cleanbar.getRating();  //fails

编辑(解决)::

final RatingBar cleanbar = (RatingBar)v.findViewById(R.id.clealiness); 

我将评级栏替换为 v 并且它有效!不知道是什么原因>.<

4

1 回答 1

2

我认为你的问题是这样的:

final RatingBar cleanbar = (RatingBar) ratingbar.findViewById(R.id.clealiness);

它不会正确初始化 RatingBar,因为您没有从 Activity 的布局(包含 RatingBar)中初始化 RatingBar,这就是您到达NPE的原因

cleanbar.getNumStars() // cleanbar is assigned as null

将其更改为

final RatingBar cleanbar = (RatingBar) findViewById(R.id.clealiness);

现在它应该可以工作了。

更新:

LayoutInflater rating = LayoutInflater.from(RatingActivity.this);
final View ratingView = rating.inflate(R.layout.rating_layout, null);

AlertDialog.Builder adb = new AlertDialog.Builder(RatingActivity.this);               
adb.setTitle("Rate us!);
adb.setView(ratingView);

AlertDialog ratingbar = adb.create();

现在为了正确获得价值:

RatingBar cleanbar = (RatingBar) ratingView.findViewById(R.id.clealiness);

您需要分配RatingBarView您膨胀。

现在它应该可以工作了:

final int cleaninput = (int) cleanbar.getRating(); 
于 2013-03-17T09:53:25.273 回答