验证android中的编辑文本

时间:2014-02-01 13:36:51

标签: android

在这段代码中我试图验证edittext和概念只允许在edittext中使用字符并在发送按钮后转发到下一页。但是如果我在editext中输入一些数字并按下Enter仍然转到下一页..请帮我解决这个问题

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

    public  static String EXTRA_MESSAGE="com.vyaap.myfirstapp.MESSAGE";
    ImageView image;
    String valid_name=null;
    EditText edittext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image =(ImageView) findViewById(R.id.imageView1);
        image.setImageResource(R.drawable.logo);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {         
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public void sendMessage(View view){
    Intent intent=new Intent(this,DisplayMessageActivity.class);
    edittext =(EditText)findViewById(R.id.edit_message);
    String message=edittext.getText().toString();
    isValidName(message);

    if(valid_name!=null){
    intent.putExtra(EXTRA_MESSAGE,valid_name);}
    startActivity(intent);
    }
    public void isValidName(String message){
    if(message.length()<0){
    edittext.setError("Accept alphabates only");    
    valid_name=null;}
    else if(!message.matches("[a-zA-Z]+")){
    valid_name=null;    
    edittext.setError("Accept alphabates only");    
    }else{
    valid_name=message; 
    }


    }
}

1 个答案:

答案 0 :(得分:1)

您在startActivity(intent)声明

之外拨打if

所以替换此

if(valid_name!=null){
intent.putExtra(EXTRA_MESSAGE,valid_name);}
startActivity(intent);

有了这个

if(valid_name!=null){
intent.putExtra(EXTRA_MESSAGE,valid_name);
startActivity(intent);
}