首先自定义Button的背景颜色并实现点击有变色效果,可参考该博客点击打开链接。有时我们需要自定义按钮样式,比如圆角按钮。
主要思路是在res文件夹下的drawable中新建两个圆角按钮背景xml,分别表示正常和按下,代码如下:
正常圆角按钮的代码:(如何设置圆角看此链接点击打开链接)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ff6501"/>
<padding android:top="10px" android:bottom="10px"/>
<corners android:radius="16px"/>
<stroke android:width="1px" android:color="#ff6501"/>
</shape>
圆角按钮按下时的代码:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#a44100"/>
<padding android:top="10px" android:bottom="10px"/>
<corners android:radius="16px"/>
<stroke android:width="1px" android:color="#a44100"/>
</shape>
再在drawable中建立一个调用这两个按钮的button_selector.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_ok" //正常按钮
android:state_pressed="false"/>
<item android:drawable="@drawable/button" //按下时的按钮
android:state_pressed="true"/>
</selector>
相应的布局文件中添加按钮控件:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="访问"
android:id="@+id/button"
android:background="@drawable/button_selector"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
这样一个自定义的圆角按钮就建立好啦!
接下来在布局文件中新建一个EditText控件:
<EditText
android:id="@+id/ed_text"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button" />
为其添加内容变化的监听事件:
editText.addTextChangedListener(textWatch);
private TextWatcher textWatch=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//s:变化前的所有字符; start:字符开始的位置; count:变化前的总字节数;after:变化后的字节数
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//S:变化后的所有字符;start:字符起始的位置;before: 变化之前的总字节数;count:变化后的字节数
}
@Override
public void afterTextChanged(Editable s) {
//s:变化后的所有字符
if(s.toString().equals("110")){
//设置按钮不可点击
bt.setClickable(true);
//设置按钮为按下状态
bt.setPressed(false);
}else{
//设置按钮可点击
bt.setClickable(false);
//设置按钮为正常状态
bt.setPressed(true);
}
}
};
注意:设置按钮是否可以点击应放在按钮监听事件之后,不然会无效,因为监听事件会自动设置按钮为可点击。
关于效果图看上面给的链接就行,差不多,只不过我们的是圆角按钮。