android 在移至另一个“活动”之前,必须输入editText字段

hpxqektj  于 2023-02-10  发布在  Android
关注(0)|答案(8)|浏览(139)

我有editText的验证。如果editText字段为空,它应该失败验证,并阻止用户移动到另一个Activity,因为需要一个值。如何做到这一点?我知道这是一个基本问题,但我不知道如何做到这一点。
我的代码:

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);
    }
});

单击此Button时,用户将被重定向到下一个屏幕,但我需要在验证失败时保持当前Activity,并且仅在验证成功(即已输入值)时转到下一个Activity

q5lcpyga

q5lcpyga1#

这很容易...检查您的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);
}

以下是Kotlin的版本:

userName.takeIf { it.isEmpty() }?.let {
  userName.error = "First name is required!"
} ?: run {
   startActivity(Intent(applicationContext, this))
}
s3fp2yjn

s3fp2yjn2#

试试这个:

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);
        }
    }
});
0aydgbwb

0aydgbwb3#

你也可以试试这个:

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);
 }
qkf9rpyu

qkf9rpyu4#

我遇到了一个类似的问题。在我的情况下,我有很多编辑文本要验证,其中一些是另一个布局的孩子。提示:所有的视图都必须在同一个根视图中。2简单地说:

...
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;
}
63lcw9qa

63lcw9qa5#

我知道这是一个老问题,但可能会有所帮助,您可以使用.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);
}
kqlmhetl

kqlmhetl6#

最好对所有必需的或特殊的验证用例使用If条件测试空的textField,并将setError作为焦点。

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

zpgglvta7#

我知道这是一篇老文章,但是我的应用程序中需要类似的功能,所以我决定开发一个简单但强大的验证器,以便于重用。
link for github repo它超级容易使用。
1.创建要设置为必填字段的列表
1.调用validateViewFields方法并传递视图列表
活动的代码示例:

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;
                }
            }
        });
    }
}
czq61nw1

czq61nw18#

活动.xml

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textLayoutProductName"
    style="@style/textInputLayout"
    app:boxStrokeColor="#ad5933"
    app:hintTextColor="#ad5933">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edTextProductName"
        style="@style/textInputEditText"
        android:hint="@string/product_name"
        android:maxLength="25" />
</com.google.android.material.textfield.TextInputLayout>

样式.xml

<style name="textInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginTop">@dimen/_5sdp</item>
    <item name="android:layout_marginLeft">@dimen/_10sdp</item>
    <item name="android:layout_marginRight">@dimen/_10sdp</item>
</style>

<style name="textInputEditText">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:maxLength">10</item>
    <item name="android:maxLines">1</item>
    <item name="android:inputType">text</item>
</style>

Activity.kt

val btnAppProduct: Button = findViewById(R.id.btnAddProduct)
val edTextProductName: TextInputEditText = findViewById(R.id.edTextProductName)
val textLayoutProductName: TextInputLayout = findViewById(R.id.textLayoutProductName)

btnAppProduct.setOnClickListener 
 {
    if (Utils().textViewEmptyChecker(textLayoutProductName,edTextProductName, "Product Name is Empty").isNotEmpty()) 
                    { //Your code here }
 }

实用工具类kt

class Utils {
fun textViewEmptyChecker(textInputLayout: TextInputLayout,
        textInputEditText: TextInputEditText,errorMsg: String): String 
        {
            if (textInputEditText.text.toString().isEmpty()) {
                textInputLayout.error = errorMsg
                textInputEditText.isFocusable = true
                textInputEditText.requestFocus()
                return ""
            }
        textInputLayout.error = null
        return textInputEditText.text.toString()
    }
}

相关问题