当在输入用户名和密码时要用到EditText组件,同时其里面输入内容的状态要对下面的注册或者登录按钮产生影响。这就要用到对EditText组件的监听。
举例如下
布局如下:
<?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">
<EditText
android:id="@+id/et_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<EditText
android:id="@+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/background_selector"
android:enabled="false"
android:text="注册"
android:textColor="@android:color/black" />
</LinearLayout>
其中的enabled的意思是:激活。
drawable文件为:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_red_small_1_p" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_red_small_1_n" android:state_enabled="true"/>
<item android:drawable="@drawable/background" android:state_enabled="false"/>
</selector>
主界面如下:
package com.jackie.app_register;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Administrator on 2016/11/6.
*/
public class FirstActivity extends Activity {
private Button button;
private EditText editText_user;
private EditText editText_pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
button = (Button)findViewById(R.id.button);
editText_pwd = (EditText)findViewById(R.id.et_pwd);
editText_user = (EditText)findViewById(R.id.et_user);
editText_pwd.addTextChangedListener(new TextChange());
editText_user.addTextChangedListener(new TextChange());
}
class TextChange implements 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) {
boolean user = editText_user.getText().length() > 0 ;
boolean pwd = editText_pwd.getText().length() > 0 ;
if ( user & pwd){
button.setEnabled(true);
}else {
button.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
}