Activity_main.
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/i1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="text"/>
<EditText
android:id="@+id/e2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"/>
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:enabled="false"
android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.java:
package com.example.p28;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText i1, e2;
private Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1 = findViewById(R.id.i1);
e2 = findViewById(R.id.e2);
b1 = findViewById(R.id.b1);
b1.setEnabled(false);
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateInputs();
}
@Override
public void afterTextChanged(Editable s) {}
};
i1.addTextChangedListener(textWatcher);
e2.addTextChangedListener(textWatcher);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = i1.getText().toString();
String password = e2.getText().toString();
if (username.equals("Aqdus") && password.equals("password")) {
Toast.makeText(MainActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Invalid Credentials",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void validateInputs() {
String username = i1.getText().toString().trim();
String password = e2.getText().toString().trim();
b1.setEnabled(!username.isEmpty() && !password.isEmpty());
}
}