0

我正在尝试将 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;
}

我有三个搜索栏,如果红色搜索栏为 0,绿色搜索栏为 0,蓝色搜索栏为 146,我想在编辑文本中显示000092etHexVal但它只显示00009。如果 RED 为 0,GREEN 为 85,BLUE 为 146,则etHexVal显示 014C9 而不是 #005592。这里出了什么问题?

4

1 回答 1

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;
}

要将字符串恢复为整数,请执行以下操作(注意:您可能希望在此处添加错误处理):

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;
}
于 2013-08-31T19:22:17.380 回答