当edittext或textview数字增加时动态添加逗号,并将单位添加到字符串末尾

时间:2019-05-12 06:58:14

标签: android textview android-edittext comma digits

我成功使用此代码在我的edittext和textview中添加了逗号。

public static void pricedigittextView(final TextView textView){
   final DecimalFormat decimalFormat = new DecimalFormat("###,###");
   final String[] result = {""};
   textView.addTextChangedListener(new TextWatcher() {
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {

       }

       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {

           if(!result[0].equals(s.toString()) && !s.toString().equals("")){
               result[0] = decimalFormat.format(Long.parseLong(s.toString().replaceAll(",", "")));   
               textView.setText(result[0]);

           }else if(s.equals("")){
               result[0] = "";
               textView.setText(result[0]);
           }
       }
       @Override
       public void afterTextChanged(Editable s) {

       }
   });

}

但是我必须添加单位(例如kg,mg)。我认为pricedigittextView()方法将String解析为Integer,并且在将String元素添加到edittext时出现错误。

我的意思是,我还有其他方法可以将数字逗号和单位动态添加到textview或edittext吗?

我尝试像s.append(“ kg”)一样在public void afterTextChanged后追加单位,但发生了相同的错误。

现在,我只是想简单地添加单元视图和操纵可见性,但这是我的最后一个计划。

任何想法或特定代码都会有所帮助!谢谢!

0 个答案:

没有答案