2013-02-08 205 views
0

的形式,我需要知道如何添加字符串以整數的形式,從而,例如,如果我需要使用setBackgroudColor(int)它可以像這樣:添加字符串爲int /添加整數的字符串

String a = "15"; // Here I mean like its user changeable , so the user can change only this part of the int; 
View.setBackgroundColor("0x" + a + "000000"); 

爲了澄清更多的,我想這兩個數字是用戶改變能改變的,還是這裏有一個例子:

1 + 1 = 2 // which is I don't want 

1 + 1 = 11 // which I want 

請幫我在這種情況下,如果你需要什麼更多的,請告訴我...

+1

所以你想要連接,正確嗎? – 2013-02-08 17:50:07

回答

0

雖然上面的答案應該做的伎倆,您的情況,你可能會看看Color.argb()方法。不知道你是如何獲取用戶輸入的,但我們只是假定他們是EditText對象:

EditText a, r, g, b; 
//initialize them 

int aInt, rInt, gInt, bInt; 

try { 
    aInt = Integer.valueOf(a.getText().toString()); 
    bInt = Integer.valueOf(b.getText().toString()); 
    cInt = Integer.valueOf(c.getText().toString()); 
    dInt = Integer.valueOf(d.getText().toString()); 
} catch (NumberFormatException ex) { 
    //Throw a warning dialog that the user's input was invalid 
} 

view.setBackgroundColor(Color.argb(aInt, rInt, gInt, bInt)); 

當然,這是假設你在0-255的整數的形式獲取輸入。

編輯:其實,如果你只是想改變它的阿爾法部分,它會容易得多。你可以從0-255的整數得到用戶的輸入,驗證它,並且這樣做:

EditText alpha; 
String alphaString; 

try { 
    alphaString = Integer.toHexString(alpha.getText().toString()); 
} catch (NumberFormatException ex) { 
    //Throw warning 
} 

view.setBackgroundColor(Color.parseColor("#" + alphaString + "000000")); 
+1

謝謝!直到現在最好的答案!正是我需要的! – Seaskyways 2013-02-08 18:51:39

1

你可以做 這直接在二進制數學。要設置ARGB,可以使用以下邏輯:

int a = 0x10; 
int r = 0x20; 
int g = 0x30; 
int b = 0x40; 

int finalColor = (a << 24) + (r << 16) + (g << 8) + b; 

鍵入0X(這是數字零和字母「X」)指的數量是十六進制格式。這意味着你可以這樣說:

int red = 0xff; // This is valid. 

我給你的邏輯允許你用十六進制指定顏色,並獲得你的顏色的int值。

操作「< <」是一個「二進制移位」,它將您的位移入正確的位置。

例如:

int x = 1; 
x = x << 1; 
// Now x is equal to 2 (since 1 shifted to the left is 10, which is 2 in binary). 

我給你上面的代碼正確地改變所有顏色。

試試這個邏輯在你的代碼:)

我可以,如果你有任何問題。

+0

我從來沒有聽說過你說的話,反正不是0x10 = 0,0x20 = 0?你可以解釋一下,或者把我連接到某個地方嗎? – Seaskyways 2013-02-08 17:53:20

+0

當然。擴大我的答案。 – WindyB 2013-02-08 17:57:21

+0

謝謝你的解釋,但是我仍然不明白這個變化很大,我現在可以工作我的東西,但我仍然沒有得到移位和二進制的東西... – Seaskyways 2013-02-08 18:37:53