Java 设置按钮背景色

Java 设置按钮背景色,java,android,Java,Android,所以我需要设置按钮的颜色。它是这样的: if (D) {Log.d(TAG, "color =" + bytes);}; int c = Color.argb(bytes[4], bytes[3], bytes[2], bytes[1]); btnStart.setBackgroundColor(c); if (D) {Log.d(TAG, "color " + by

所以我需要设置按钮的颜色。它是这样的:

    if (D) {Log.d(TAG, "color =" + bytes);};
                    int c = Color.argb(bytes[4], bytes[3], bytes[2],  bytes[1]);
                    btnStart.setBackgroundColor(c);
                    if (D) {Log.d(TAG, "color " + bytes[4]+ bytes[3]+bytes[2]+ bytes[1]);};
                    break;
我向LogCat获得以下输出: 颜色=[B@40534710 颜色-1-1-1-1 这是怎么发生的?我希望在数组中看到一些其他值,而不是-1

下面是完整的代码

    mainHandler=new Handler(){
        public void handleMessage(Message msg) {    
            switch (msg.what){
            case TOAST:
                Bundle bundle = msg.getData();
                String string = bundle.getString("myKey");
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
                break;
            case NEW_SMS:
                if (D) {Log.d(TAG, "newSms recieved");}
                byte[] bytes =(byte[]) msg.obj;
                switch (bytes[0]){
                case SMS_TEXT:
                    bytes = shiftArrayToLeft(bytes);
                    String readMessage = new String(bytes, 0, msg.arg1);
                    txtView.setText(readMessage);
                    break;
                case SMS_COLOR:
                    if (D) {Log.d(TAG, "color =" + bytes);};
                    //LinearLayout lLayout = (LinearLayout) findViewById(R.id.lLayout);
                    int c = Color.argb(bytes[4], bytes[3], bytes[2],  bytes[1]);
                    btnStart.setBackgroundColor(c);
                    if (D) {Log.d(TAG, "color " + bytes[4]+ bytes[3]+bytes[2]+ bytes[1]);};
                    break;
                }

            }
    }};

这是一个处理蓝牙消息的处理程序,您的
字节数组的类型是什么?如果它是
字节[]
数组,那么您就有问题了,因为
字节
s是带符号整数,范围从-128到127,而
Color.argb()
构造函数要求在0到255的范围内有4个
int
s。这意味着如果字节数组的任何元素包含负值,则调用
Color.argb()
将失败。文档说明:

这些组件值应为[0..255],但没有执行范围检查,因此如果它们超出范围,则返回的颜色未定义

无论如何,Java中没有无符号字节类型,因此您必须手动确保将值从-128到127范围转换为0到255范围内的整数。类似的操作应该可以:

int c = Color.argb(((int)bytes[4]) % 256, ((int)bytes[3]) % 256, ((int)bytes[2]) % 256,  ((int)bytes[1]) % 256);

可能有一个更优雅的解决方案,但这至少会确认这是否是您的问题。

字节从何而来?此外,要创建颜色,您需要整数,而不是字节。