gpt4 book ai didi

java - 在android中每个逗号限制为六个字符

转载 作者:行者123 更新时间:2023-11-29 09:16:29 25 4
gpt4 key购买 nike

我需要在 android 的编辑文本中限制逗号后的六个字符,我应该能够为逗号添加字符...

即 3000,898989,898345...3000 可以是 30000 或 300000...无限但逗号后的字符应固定为六个...

在编辑文本中每个逗号后只能输入六个字符...

怎么办?

我试过以下内容

public class CustomEditTextActivity extends Activity {

EditText et;
Context cn=null;
int commacount=0;
String aftercomma;
boolean flag=false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cn=this;
et=(EditText)findViewById(R.id.editText1);

// Listener for edit text text change
et.addTextChangedListener(filterTextWatcher);


}

private TextWatcher filterTextWatcher = new TextWatcher() {

public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub

System.out.println("Inside afterTextChanged() method");



}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {

System.out.println("Inside beforeTextChanged() method");


}

public void onTextChanged(CharSequence s, int start, int before,
int count) {
flag=false;
commacount=0;
String getDataFromeditxt = s.toString();
int comma = getDataFromeditxt.indexOf(',');
String bforcomma = getDataFromeditxt;
if (comma != -1)
{
bforcomma = getDataFromeditxt.substring(0, comma);
}



// Checking for , in the data and setting its position
for (int i = 0; i < getDataFromeditxt.length(); i++) {
char c = getDataFromeditxt.charAt(i);
if(flag){
aftercomma=new StringBuilder().append(c).toString();
int maxLength =bforcomma.length() +6+commacount;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
et.setFilters(FilterArray);
System.out.println(aftercomma);

}
if (c == ',') {
commacount=commacount+1 ;
flag=true;
}

}

}

};

上面代码中的问题是,一旦设置了 maxlength,我就不能输入任何内容……有什么解决办法吗??

最佳答案

Use pattern matching in java. Replace str with text from editext.
String result="";
String str= "300066666666666666666,898989,898345,000000,111111,333333";//editext.getText().toString();
String regex ="(^[0-9]+)([,]+[0-9]{6})+$";
Matcher matcher = Pattern.compile( regex ).matcher( str);
if (matcher.find( ))
{
result = matcher.group();
System.out.println("number="+result);
}
else
{
System.out.println("no match found");
}
output
number=300066666666666666666,898989,898345,000000,111111,333333

关于java - 在android中每个逗号限制为六个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com