开发者

Help need example android regular expression accept only number in EditText !

Every one I nee开发者_运维技巧d example in android that allow user type only number in my EditText (password) thx !


A regex to test if an input is made up of just numbers would simply be: ^[0-9]*$


MainActivity

public class MainActivity extends Activity {
EditText ed;
Button b;
String input;
String result;
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b=(Button) findViewById(R.id.bt);
    ed=(EditText) findViewById(R.id.ed1);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View arg0) {

            input = ed.getText().toString();
             String regex ="^[0-9]+$";
                Matcher matcher = Pattern.compile( regex ).matcher(input);
                if (matcher.find( ))
                {
                result = matcher.group(); 
                Toast.makeText(MainActivity.this, "Matches",1000 ).show();
                System.out.println("number="+result);            
                }
                else
                {
                    Toast.makeText(MainActivity.this, " No Matches",1000 ).show();
                     System.out.println("no match found"); 
                }
        }       
    });
}
}

Your xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:padding="@dimen/padding_medium"
    android:text="@string/hello_world"
    tools:context=".MainActivity" />
<EditText
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:id="@+id/ed1"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="submit"
    android:id="@+id/bt"
    />
 </LinearLayout>


Maybe a wild goose chase, You can configure EditText input for numeric and set password to true.

<EditText android:inputType="number"
android:id="@+id/EditText01"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:password="true" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜