我分配了一个任务,要在Android Studio中构建一个简单的多窗口小部件应用程序,并且我试图弄清楚如何在一个类中为多页照片评级应用程序声明多个变量。我有4页,以及4张照片,每张照片下面都有一个RatingBar
。我想将所有评分的平均值显示在页面顶部。为简单起见,我使用SetTitle
如何编写这种Java以便可以访问所有4个等级并将基本数学应用于它们?从技术上讲,这超出了我们迄今为止在本课程中所学的内容。
package ca.bcit.comp2052.a00587366.multiplewidgetsapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start of rating bar
RatingBar ratingBar1 = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar1, float rating, boolean fromUser) {
// Implement your logic here
float total = 0;
total += ratingBar1.getRating();
// total += ratingBar2.getRating();
// total += ratingBar3.getRating();
// total += ratingBar4.getRating();
float average = total / 4;
setTitle("Average: " + average);
}
});
// end of rating bar
Button buttonNext = (Button) findViewById(R.id.nextButton);
buttonNext.setOnClickListener(new
android.view.View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,
Main2Activity.class));
}
});
}
}
答案 0 :(得分:1)
您可能应该将它们设置为R.id.ratingBars[0]
,依此类推,但是由于您没有,假设它是R.id.ratingBar1
至R.id.ratingBar4
,您可以执行以下操作:
final RatingBar[] ratingBars = {
(RatingBar) findViewById(R.id.ratingBar1),
(RatingBar) findViewById(R.id.ratingBar2),
(RatingBar) findViewById(R.id.ratingBar3),
(RatingBar) findViewById(R.id.ratingBar4)
};
for (final RatingBar ratingBar : ratingBars) {
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar bar, float rating, boolean fromUser) {
// Implement your logic here
float total = 0.0f;
for (final RatingBar ratingBar : ratingBars) {
total += ratingBar.getRating();
}
float average = total / 4.0f;
setTitle("Average: " + average);
}
});
}
如果需要,这也使添加新RatingBar
更加容易。您只需将它们添加到顶部的原始数组初始化列表中,一切都将得到处理。
答案 1 :(得分:0)
您可以尝试通过
致电给他们Main2Activity.ratingBar2.getRating()
但是它们应该是公开的,这不太好。
在其他地方,您可以将其声明为私有,并创建公共getter方法以从外部类中检索它们。