繁体   English   中英

设置按钮背景色

[英]setting button background color

因此,我尝试设置按钮颜色。 它是这样的:

    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:color = [B @ 40534710 color -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;
                }

            }
    }};

这是处理蓝牙消息的处理程序

您的bytes数组类型是什么? 如果它是byte[]的数组,那么您会遇到问题,因为byte是带符号的整数,范围为-128至127,而Color.argb()构造函数期望4 int的范围为0至255。这意味着,如果字节数组的任何元素包含负值,则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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM