2014-09-13 183 views
1

我想在editText中的一個千分隔符(,),當我在editText鍵入。 之後,我會對數字進行一些操作,然後在千位分隔符(,)的TextView中顯示結果。「編輯文本和TextView」格式與千位分隔符(,)在android

這是我的代碼:

public class Mainactivity extends Activity { 

/** Called when the activity is first created. */ 

EditText  edt; 
TextView  txt; 
Button   btn; 

OnClickListener myclick = new OnClickListener() { 

          @Override 
          public void onClick(View arg0) { 

           // my calculation 
           double num1 = Double.parseDouble(edt.getText().toString()); 
           double num2 = num1 + 7; 

           txt.setText("" + num2); 

          } 
         }; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    edt = (EditText) findViewById(R.id.edt); 
    txt = (TextView) findViewById(R.id.txt); 
    btn = (Button) findViewById(R.id.btn); 

    btn.setOnClickListener(myclick); 

} 

}

+1

你可以使用 [答案http://stackoverflow.com/questions/12338445/how-to-automatically-添加千隔板-AS-數是輸入合的EditText] [1] [1]:http://stackoverflow.com/questions/12338445/how-to-automatically-add -千-separators-as-number-is-input-in-edittext – JoaoBiriba 2014-09-13 13:32:05

回答

6

您可以使用

String value=String.format("%,.2f", num); 

的數量解析爲String與千位分隔符,然後將結果設置爲TextView的或您想要的EditText

例如:

txt.setText(String.format("%,.2f", num)); 
edt.setText(String.format("%,.2f", num)); 
+0

這對textView很有用,但是對於EditText,我想單獨輸入值。 – nasim12w 2014-09-14 08:06:38

1

嘗試使用此代碼

 @Override 
     public void afterTextChanged(Editable s) { 

      try 
      { 
       edittext.removeTextChangedListener(this); 
       String value = edittext.getText().toString(); 
       if (value != null && !value.equals("")) 
       { 
        String str = edittext.getText().toString().replaceAll(",", ""); 
        if (value != null && !value.equals("")) 
         Double.valueOf(str).doubleValue(); 
        edittext.setText(getDecimalFormat(str)); 
        edittext.setSelection(edittext.getText().toString().length()); 
       } 
       edittex.addTextChangedListener(this); 
       return; 
      } 
      catch (Exception localException) 
      { 
       localException.printStackTrace(); 
       edittext.addTextChangedListener(this); 
      } 
     } 

private String getDecimalFormat(String value) 
{ 
    StringTokenizer lst = new StringTokenizer(value, "."); 
    String str1 = value; 
    String str2 = ""; 
    if (lst.countTokens() > 1) 
    { 
     str1 = lst.nextToken(); 
     str2 = lst.nextToken(); 
    } 
    String str3 = ""; 
    int i = 0; 
    int j = -1 + str1.length(); 
    if (str1.charAt(-1 + str1.length()) == '.') 
    { 
     j--; 
     str3 = "."; 
    } 
    for (int k = j;; k--) 
    { 
     if (k < 0) 
     { 
      if (str2.length() > 0) 
       str3 = str3 + "." + str2; 
      return str3; 
     } 
     if (i == 3) 
     { 
      str3 = "," + str3; 
      i = 0; 
     } 
     str3 = str1.charAt(k) + str3; 
     i++; 
    } 
} 

希望幫助您