[英]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.