Android中的Button自定义点击效果实例代码
程序员文章站
2023-12-04 21:22:22
方法一1.放在drawable下的selector.xml文件复制代码 代码如下:
<android="http://schemas.android.com/apk/res/android">
android:drawable="@drawable/temp2" />
<http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<android:drawabletop="@drawable/shouru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:background="@drawable/selector"/>
2.主要的java代码,实现点击效果:
button button = (button) this.findviewbyid(r.id.button);
button.setontouchlistener(new button.ontouchlistener(){
@override
public boolean ontouch(view v, motionevent event) {
if(event.getaction() == motionevent.action_down){
v.setbackgroundresource(r.drawable.temp1);
log.i("testandroid button", "motionevent.action_down");
}
else if(event.getaction() == motionevent.action_up){
v.setbackgroundresource(r.drawable.temp2);
log.i("testandroid button", "motionevent.action_up");
}
return false;
}
});
方法一
1.放在drawable下的selector.xml文件
复制代码 代码如下:
<android="http://schemas.android.com/apk/res/android">
android:drawable="@drawable/temp2" />
2.布局文件main.xml
复制代码 代码如下:
<http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<android:drawabletop="@drawable/shouru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:background="@drawable/selector"/>
方法二
1.布局文件main.xml
[code]
<http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<android:id="@+id/button"
android:drawabletop="@drawable/shouru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:background="@drawable/temp4"/>
2.主要的java代码,实现点击效果:
复制代码 代码如下:
button button = (button) this.findviewbyid(r.id.button);
button.setontouchlistener(new button.ontouchlistener(){
@override
public boolean ontouch(view v, motionevent event) {
if(event.getaction() == motionevent.action_down){
v.setbackgroundresource(r.drawable.temp1);
log.i("testandroid button", "motionevent.action_down");
}
else if(event.getaction() == motionevent.action_up){
v.setbackgroundresource(r.drawable.temp2);
log.i("testandroid button", "motionevent.action_up");
}
return false;
}
});