我是java方面的真正新手,尤其是面向对象编程,所以我将不胜感激。
我已经创建了功能,可以更改每个评级栏选择的颜色,并且由于我想在很少的其他评级栏上重用此功能,因此我尝试在方法中插入整个代码每个对象的名称和资源 id 作为参数,但我显然不知道我在做什么,因为我收到错误,名称变量已在范围中定义,并且 findViewById 是非静态方法并从静态上下文调用。
//rating bar
static void starLight(String name, int resId) {
RatingBar name = (RatingBar) findViewById(resId);
name.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float
rating, boolean fromUser) {
int whole = Math.round(rating);
Drawable progress = ratingBar.getProgressDrawable();
if (whole == 1) {
DrawableCompat.setTint(progress,
ResourcesCompat.getColor(getResources(), R.color.colorGreen, null));
}
if (whole == 2) {
DrawableCompat.setTint(progress,
ResourcesCompat.getColor(getResources(), R.color.colorOrange, null));
}
if (whole == 3) {
DrawableCompat.setTint(progress,
ResourcesCompat.getColor(getResources(), R.color.colorRed, null));
}
}
});
}
如果您能给我一些启发或为我指出正确的方向,我将非常感激。
最佳答案
为什么不传递特定的RatingBar而不是资源id?然后您可以将方法签名保留为静态。正如其他人指出的那样,不需要 String name
参数。像这样:
static int green = ResourcesCompat.getColor(getResources(), R.color.colorGreen, null));
static void starLight(RatingBar ratingBar) {
Drawable progress = ratingBar.getProgressDrawable();
if (whole == 1) {
DrawableCompat.setTint(progress, green);
...}
关于java - 重用部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593703/