如何在Android上获取按钮的背景颜色?

7
我希望获取按钮的颜色。我无法从getbackground函数中获取颜色,该函数返回Drawable对象。我使用了getsolidcolor函数,它返回整数值,但始终为0。我不知道问题出在哪里,可能是函数不正确。
以下是我的Android代码:
            int renk = btn1.getSolidColor();

        if(renk== Color.GREEN)
            Toast.makeText(getApplicationContext(), "green" , 1000).show();
        else if(renk== Color.RED)
            Toast.makeText(getApplicationContext(), "red" , 1000).show();
        else if(renk== Color.YELLOW)
            Toast.makeText(getApplicationContext(), "yellow" , 1000).show();
        else
            Toast.makeText(getApplicationContext(), "unknown", 1000).show();

        btn1.setBackgroundColor(Color.YELLOW);
     renk = btn1.getSolidColor();


        if(renk== Color.GREEN)
            Toast.makeText(getApplicationContext(), "green" , 1000).show();
        else if(renk== Color.RED)
            Toast.makeText(getApplicationContext(), "red" , 1000).show();
        else if(renk== Color.YELLOW)
            Toast.makeText(getApplicationContext(), "yellow" , 1000).show();
        else
            Toast.makeText(getApplicationContext(), "unknown", 1000).show();

即使我将背景设置为黄色,我仍然收到未知的提示消息。

1个回答

8

给你 ...

 Button myButton = (Button) findViewById(R.id.takePicture);

 myButton.setBackgroundDrawable(new PaintDrawable(Color.YELLOW));

 PaintDrawable drawable = (PaintDrawable) myButton.getBackground();

 int color = drawable.getPaint().getColor();

这不会一直返回黄色吗? - Matthias
2
我曾将 ((ColorDrawable) row.getBackground()).getColor() 转换为 (row.background as ColorDrawable).color,但是我遇到了这个错误 android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.ColorDrawable - milad salimi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接