Android 在转到另一个活动之前需要 editText 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11535011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:56:42  来源:igfitidea点击:

editText field is required before moving on to another Activity

androidvalidationandroid-edittextonclicklistener

提问by Krishna Veni

I have validation for editText. If the editTextfield is empty it should fail validation and stop the user moving on to another Activity, as a value is required. How to do it? I know this is a basic question, but I can't figure out how to do this.

我有editText. 如果该editText字段为空,则验证失败并停止用户移动到另一个Activity,因为需要一个值。怎么做?我知道这是一个基本问题,但我不知道如何做到这一点。

My code:

我的代码:

btninsert = (Button)findViewById(R.id.btn_insert);
btninsert.setOnClickListener( new View.OnClickListener() {
    public void onClick(View v) {
        insertValues();
        EditText userName = (EditText) findViewById(R.id.editText1);

        if( userName.getText().toString().length() == 0 )
            userName.setError( "First name is required!" );

        Intent i = new Intent(getApplicationContext(), Login.class);
        startActivity(i);
    }
});

When this Buttonis clicked the user is redirect to next screen, but I need that if validation fails they stay on the current Activity, and only when validation is successful (i.e. a value has been entered) they go to the next Activity.

当此Button点击用户重定向到下一个画面,但我需要,如果验证失败,他们停留在当前Activity,只有当验证成功(即值已进入),他们去下Activity

回答by Haresh Chaudhary

It's easy...check if your EditText is empty as in below example below.

这很容易...检查您的 EditText 是否为空,如下面的示例所示。

if( TextUtils.isEmpty(userName.getText())){
   /**
    *   You can Toast a message here that the Username is Empty    
    **/

   userName.setError( "First name is required!" );

}else{
   Intent i = new Intent(getApplicationContext(), Login.class);
   startActivity(i);
}

回答by Rajender Reddy

Try this:

尝试这个:

bt.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0)
    {
        String  str=et.getText().toString();

        if(str.equalsIgnoreCase(""))
        {
            et.setHint("please enter username");//it gives user to hint
            et.setError("please enter username");//it gives user to info message //use any one //
        }
        else
        {
            Intent in=new Intent(getApplicationContext(),second.class);
            startActivity(in);
        }
    }
});

回答by fidazik

You can also try this:

你也可以试试这个:

 if ( ( userName.getText().toString().trim().equals("")) ) 
 {
      Toast.makeText(getApplicationContext(), "User name is empty", Toast.LENGTH_SHORT).show();
 }
 else
 {
      Intent i = new Intent(getApplicationContext(), Login.class);
      startActivity(i);
 }

回答by XIII

I understand it's an old question but may this helps, you can use .isEmpty() instead of .equals()

我知道这是一个老问题,但这可能会有所帮助,您可以使用 .isEmpty() 而不是 .equals()

if( userName.getText().toString().isEmpty()){

   /**
    *   You can Toast a message here that the Username is Empty    
    **/

   userName.setError( "First name is required!" );

}else{
   Intent i = new Intent(getApplicationContext(), Login.class);
   startActivity(i);
}

回答by Akshay Mishra

Better to test empty textField using If condition for all required or special validation cases and setError to focus.

最好使用 If 条件测试所有必需或特殊验证情况的空 textField 并设置错误以聚焦。

If(txtName.getText().toString().trim().equals(""))
{
//Your message or any other validation
}

回答by Leonardo Costa

I faced a similiar problem. In my case, I had a lot of Edittexts to verify, some them was child of another layouts. Tip: all views must be in same root view. So, to be simple:

我遇到了类似的问题。就我而言,我有很多 Edittext 需要验证,其中一些是其他布局的子项。提示:所有视图必须在同一个根视图中。所以,简单来说:

...
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
checkFieldsRequired(viewGroup);
...

public boolean checkFieldsRequired(ViewGroup viewGroup){

    int count = viewGroup.getChildCount();
    for (int i = 0; i < count; i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof ViewGroup)
            checkFieldsRequired((ViewGroup) view);
        else if (view instanceof EditText) {
            EditText edittext = (EditText) view;
            if (edittext.getText().toString().trim().equals("")) {                  
                edittext.setError("Required!");                 
            }
        }
    }

    return false;
}

回答by Omar Gharra

I know this is an old post, but I needed similar functionality in my application, so I deciced to develop a simple but powerful validator for ease of re-use.

我知道这是一篇旧帖子,但我的应用程序需要类似的功能,因此我决定开发一个简单但功能强大的验证器以方便重用。

link for github repoIt's super easy to use.

github repo链接它非常易于使用。

  1. Create a list of the fields you want to be mandatory
  2. Call validateViewFieldsmethod and pass the list of views
  1. 创建您希望成为必填字段的列表
  2. 调用validateViewFields方法并传递视图列表

code example for Activity:

活动代码示例:

    public class AddContractActivity extends AppCompatActivity {

    TextView contractDescriptionTextView;
    TextView totalAmountTextView;

    List<View> fieldsToBeValidated;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contract);

        contractDescriptionTextView = findViewById(R.id.contractDescriptionEditText);
        totalAmountTextView = findViewById(R.id.totalAmountText);

        fieldsToBeValidated = new ArrayList<>(Arrays.asList(
                contractDescriptionTextView,
                totalAmountTextView));

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UIValidator.validateViewFields(fieldsToBeValidated, true)) {
                    Toast.makeText(AddContractActivity.this, "Missing Fields", Toast.LENGTH_SHORT).show();
                    mainScrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            mainScrollView.smoothScrollTo(0, 0);
                        }
                    });
                    return;
                }
            }
        });
    }
}