EditText为空时Button按钮无效

一、activity_main.xml

<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.weicy.dailimoshi.MainActivity">
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入名字"
        android:layout_margin="5dp"
        />
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:layout_margin="5dp"
        />
    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="提交"
        android:layout_margin="5dp"
        android:enabled="false"
        />
</LinearLayout>
二、Mainactivity

name = findViewById(R.id.name);
password = findViewById(R.id.password);
submit = findViewById(R.id.submit);
//判断用户名
name.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(name.getText()) || TextUtils.isEmpty(password.getText())) {
            submit.setEnabled(Boolean.FALSE);
            Toast.makeText(MainActivity.this, "按钮不可点击", Toast.LENGTH_SHORT).show();
        } else {
            submit.setEnabled(Boolean.TRUE);
            Toast.makeText(MainActivity.this, "按钮可点击", Toast.LENGTH_SHORT).show();
        }

    }

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

    @Override
    public void afterTextChanged(Editable s) {
    }
});
//判断密码
password.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(name.getText()) || TextUtils.isEmpty(password.getText())) {
            submit.setEnabled(Boolean.FALSE);
            Toast.makeText(MainActivity.this, "按钮不可点击", Toast.LENGTH_SHORT).show();
        } else {
            submit.setEnabled(Boolean.TRUE);
            Toast.makeText(MainActivity.this, "按钮可点击", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});
//点击事件
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "按钮", Toast.LENGTH_SHORT).show();
    }
});

猜你喜欢

转载自blog.csdn.net/weikai_/article/details/79269777
今日推荐