java - 重用部分代码

标签 java android class methods

我是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/

相关文章:

java - JCombobox Listener如何在选择项目时启用它?

java - 如何使用 ListIterator 打印数组列表中节点的数据字段

android - 最初使用 ServerValue.TIMESTAMP 和 Android 设置时如何从 Firebase 数据库检索本地 TIMESTAMP?

c++ - 不可用的公共(public)变量

java - 从抽象类和子类java创建对象数组

java - 如何查找缺少哪些 Maven 依赖项

java - 你如何在 .net 上运行 Lucene?

安卓科拉达

android - 在 Scroll Flutter 上隐藏 Appbar?

java - "Exception in thread "Animation Thread”在Eclipse中使用Processing时出错