android 自定义button背景图片及事件——自定义控件学习(一)
在学习了基本控件之后,需要了解自定义控件的定义方法。原因是这样的,如果做一个下拉刷新,需要把整个ListView的下拉刷新代码写到业务中,那么代码会非常的乱,不利于后期的修改和处理。所以应该尝试把一些常用的功能,或者项目中经常使用的功能放到自定义控件中,然后直接使用自定义控件就行啦,好下面上货。
下面,就以一个自定义button的例子抛砖引玉。
1、自定义button,MyButton。
package com.example.administrator.customerbutton;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
/**
* Created by Administrator on 2016-09-26.
*/
public class MyButton extends Button{
private int bitmapDownId;
private int bitmapUpId;
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
Log.i("---->","---->" + keyCode);
return false;
}
public void setBackgroundImage(int bitmapDownId,int bitmapUpId){
this.bitmapDownId = bitmapDownId;
this.bitmapUpId = bitmapUpId;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
this.setBackgroundResource(bitmapDownId);
break;
case MotionEvent.ACTION_UP:
this.setBackgroundResource(bitmapUpId);
break;
}
return super.onTouchEvent(event);
}
}
2、在MainActivity布局文件中使用:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.customerbutton.MainActivity">
<com.example.administrator.customerbutton.MyButton
android:id="@+id/mybutton"
android:layout_width="60dp"
android:layout_centerHorizontal="true"
android:layout_height="30dp" />
</RelativeLayout>
3、MianActivity.java中设置一下,然后进行显示button。
package com.example.administrator.customerbutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
private MyButton myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (MyButton)this.findViewById(R.id.mybutton);
myButton.setBackgroundResource(R.drawable.button2);
myButton.setBackgroundImage(R.drawable.button1,R.drawable.button2);
myButton.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (event.getAction()){
case KeyEvent.ACTION_DOWN:
Log.i(TAG,"---->>>>MainActivity_key_down" + keyCode);
break;
case KeyEvent.ACTION_UP:
Log.i(TAG,"---->>>>MainActivity_key_up" + keyCode);
break;
}
return false;
}
});
}
}
4、下面测试一下,首先是按下和抬起的时候button的变化:
5、测试一下keydown事件。
点击按钮,然后按键盘上的按键。