获取按钮的背景颜色

时间:2014-07-30 21:10:24

标签: android view colors

我正在尝试比较按钮的颜色,我已经分配了两种颜色android.R.color.holo_orange_darkandroid.R.color.holo_blue_dark。它给出int值为负按钮的背景颜色。 这是我的代码

public class MainActivity extends Activity implements OnClickListener{

    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private Button btnEmpty;
    private ColorDrawable btnColor;
    private int colorId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ini();
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);          
    }

    /**
     * 
     * 
     */
    private void ini() {        
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);
        btn8 = (Button) findViewById(R.id.btn8);
        btnEmpty = (Button) findViewById(R.id.btnEmpty);
        btnEmpty.setOnClickListener(this);
    }

    @Override
    public void onClick(View btn) {
        switch (btn.getId()) {
        case R.id.btn1:
            btnColor = (ColorDrawable) btn2.getBackground();
            colorId = btnColor.getColor();
            if (colorId == android.R.color.holo_blue_dark) { 
                    Toast.makeText(MainActivity.this, "Color is holo_blue_dark", Toast.LENGTH_LONG).show();
            }else{
                    Toast.makeText(MainActivity.this, "Color is holo_orange_dark", Toast.LENGTH_LONG).show();

            }               
            break;
        }

    }

} }

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

颜色的int值与颜色的资源标识符不同,它可能是负数。请尝试以下方法:

if (colorId == getResources().getColor(android.R.color.holo_blue_dark))