如何在android上获得按钮的背景颜色?

unb*_*ced 7 android background-color

我想获得按钮的颜色..我无法从返回drawable的getbackground函数获得颜色.我使用了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();
Run Code Online (Sandbox Code Playgroud)

即使我将背景设置为黄色,我也会得到未知的吐司消息.

Lai*_*gem 8

你去......

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

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

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

 int color = drawable.getPaint().getColor();
Run Code Online (Sandbox Code Playgroud)

  • 我使用这个 `((ColorDrawable) row.getBackground()).getColor()` 作为 `(row.background as ColorDrawable).color` 但我遇到了这个错误 `android.graphics.drawable.StateListDrawable 无法转换为 android .graphics.drawable.ColorDrawable` (2认同)