重用部分代码

时间:2017-04-24 16:47:48

标签: java android class methods

我是java中的一个真正的新手,尤其是这个面向编程的对象,所以我会感激任何输入。

我已经制作了功能,在每个选择的评级栏上改变了颜色,并且由于我想要重用此功能的其他评级栏很少,我试图在方法中插入整个代码每个对象的名称和资源id作为参数,但我显然不知道我在做什么,因为我在范围中已经定义了名称变量的错误,并且findViewById是非静态方法并且是从静态上下文调用的。

WITH tableC
AS
(


SELECT personID,
   person,
   datekey,
   date,
   SUM(sales) AS sales,
   NULL AS costs
FROM tableA
GROUP BY personID, person, datekey, date

UNION ALL

SELECT personID,
   person,
   datekey,
   date,
   NULL,
   SUM(costs) AS costs
FROM tableB
GROUP BY personID, person, datekey, date

)


SELECT personID,
   person,
   datekey,
   date,
   ISNULL(SUM(sales), 0) AS sales,
   ISNULL(SUM(costs),0) AS costs
FROM tableC
GROUP BY personID, person, datekey, date
ORDER BY datekey

如果你能说出一些亮点或指出我正确的方向,我将非常感激。

2 个答案:

答案 0 :(得分:1)

您似乎只需要更改函数签名并删除String参数:

static void starLight(/*String name,*/ int resId) {

我不知道你打算用它做什么,但似乎你实际上并没有将它用于任何事情。

您遇到编译器错误的原因是因为您有两个名为' name'的变量:一个作为参数,一个作为方法体内的局部变量。

作为旁注,您当前的版本会复制很多代码。你可以重构这个:

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));
}
// etc.

类似

Drawable progress = ratingBar.getProgressDrawable();
int colour;
switch (whole)
{
    case 1:
        colour = R.color.colorGreen;
        break;
    case 2:
        colour = R.color.colorOrange;
        break;
    case 3:
        colour = R.color.colorRed;
        break;
    default:
        colour = //something. Or throw an exception maybe?
}
DrawableCompat.setTint(progress, ResourcesCompat.getColor(getResources(), colour, null));

有趣的是,这最终会比你现在所拥有的更长,但是我认为它更容易看到发生了什么,因为信息有点像密度较小。此外,如果您更改设置色调的方式,现在只需要在一个位置进行。

答案 1 :(得分:1)

为什么不传入特定的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);
...}