Android-Toast:无法吐出RatingBars的平均值

时间:2014-06-02 04:35:13

标签: android ratingbar android-toast

我尝试使用Toast显示3个ratingBars的平均值,但它总是显示0.0。我也尝试将平均值转换为String但没有运气。请帮忙。这是我的代码:

float rating1 = ratingBar.getRating();
float rating2 = ratingBar2.getRating();
float rating3 = ratingBar3.getRating();
float average = (rating1+rating2+rating3) / 3;

final String formatFloat = Float.toString(average);

Button button1 = (Button) rootView.findViewById(R.id.button1);
button1.setOnClickListener(new android.view.View.OnClickListener() {
    public void onClick(View v) {
    // Implement your logic here

    Toast.makeText(PlaceholderFragment.this.getActivity(),formatFloat, 
                        Toast.LENGTH_SHORT).show();             
    }
});

4 个答案:

答案 0 :(得分:1)

看起来你正在失去精确度。试试这个:

float average = (rating1+rating2+rating3) / (float)3;

答案 1 :(得分:1)

按钮代码将被执行,直到用户点击该按钮,所有先前的代码将在按钮设置之前执行。评级栏何时更改?按钮设置之前还是之前?我会做的

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new android.view.View.OnClickListener() {
  public void onClick(View v) {
    float rating1 = ratingBar1.getRating();
    float rating2 = ratingBar2.getRating();
    float rating3 = ratingBar3.getRating();
    float average = (rating1 + rating2 + rating3) / 3.0f;
    String formatFloat = Float.toString(average);
    Toast.makeText(PlaceholderFragment.this.getActivity(),formatFloat,
                   Toast.LENGTH_SHORT).show();
  }
}

当用户点击按钮时,要确保评级是最新值,否则,如果在用户更改评级栏之前执行代码,则代码,rating1,rating2和rating3可以全为0。

答案 2 :(得分:0)

我通过输入硬代码值来尝试此代码并且它运行良好

    float rating1 = 13.4f;
    float rating2 = 12.6f;
    float rating3 = 19.5f;
    float average = (float) ((rating1 + rating2 + rating3) / 3);

    final String formatFloat = Float.toString(average);

    Log.i("mini", "Rating:"+formatFloat);

试试这个!!!

答案 3 :(得分:0)

您是否可以在setOnClickListener内添加评分的计算部分并检查?如下所示。

Button button1 = (Button) rootView.findViewById(R.id.button1);
button1.setOnClickListener(new android.view.View.OnClickListener() {
    public void onClick(View v) {
    // Implement your logic here

float rating1 = ratingBar.getRating();
float rating2 = ratingBar2.getRating();
float rating3 = ratingBar3.getRating();
float average = (float)((rating1+rating2+rating3) / 3);

    Toast.makeText(getApplicationContext(),average + "", 
                        Toast.LENGTH_SHORT).show();             
    }
});