我正在尝试将RGB转换为HEX,但保存Hex值的EditText未显示0
这是我的代码:
etHexVal = (EditText) findViewById(R.id.etHex);
if (etHexVal.length() == 6) { //has 000000
}
if (etHexVal.length() < 6) { //anything else
Toast.makeText(getApplicationContext(), "Please enter SIX characters/numbers combination", 2000).show();
}
etHexVal.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String filtered_str = s.toString();
if (filtered_str.matches(".*[^A-F^0-9].*")) {
filtered_str = filtered_str.replaceAll("[^A-F^0-9]", "");
s.clear();
s.append(filtered_str);
Toast.makeText(getApplicationContext(), "Only A-F and 0-9 is allowed", 2000).show();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
private int getColorFromSeekbars()
{
return Color.argb(255, redSeek.getProgress(), greenSeek.getProgress(), blueSeek.getProgress());
}
private String displayHexVal() {
String k = "" + redSeek.getProgress() + greenSeek.getProgress() + blueSeek.getProgress() + "";
Toast.makeText(getApplicationContext(), k, 2000).show();
String strColor = String.format("#%06X", 0xFFFFFF & Integer.valueOf(k));
return strColor;
}
我有三个Seekbars,如果RED seekbar为0且GREEN seekbar为0且BLUE seekbar为146,我想在000092
edittext中显示etHexVal
,但它只显示00009
。如果RED为0,则GREEN为85,BLUE为146,etHexVal
显示014C9而不是#005592。这里出了什么问题?
答案 0 :(得分:2)
如果我理解你的问题,那么你的字符串中没有得到正确的值。尝试执行以下操作:
在你的displayHexVal()中将String k ...
替换为:
public String k = getHexFromInt(redSeek.getProgress()) + getHexFromInt(greenSeek.getProgress()) + getHexFromInt(blueSeek.getProgress());
并添加以下方法:
public String getHexFromInt(int val){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
if (sb.length() < 2) {
sb.insert(0, '0'); // add leading zero if necessary
}
String hex = sb.toString();
return hex;
}
要将String恢复为int,请执行以下操作(注意:您可能需要在此处添加错误处理):
public int[] getIntsFromHex(String hex){
int[] results = new int[3];
results[0] = Integer.parseInt(hex.substring(0,2),16);
results[1] = Integer.parseInt(hex.substring(2,4),16);
results[2] = Integer.parseInt(hex.substring(4,6),16);
return results;
}