以定义一个ImageView为例。
1.定义一个layout.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/img_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="5dip"
android:paddingTop="5dip"/>
</LinearLayout>
2.定义一个控件类,导入布局,即导入layout.xml
public class ButtonArrow extends LinearLayout {
private ImageView mImgView = null;
public ButtonArrow(Context context, AttributeSet attrs) {
super(context, attrs);
//导入布局
LayoutInflater.from(context).inflate(R.layout.button_arrow,this,true);
mImgView = (ImageView)findViewById(R.id.img_arrow);
}
public void setImageRes( int resId){
mImgView.setImageResource( resId );
}
3.使用控件
private ButtonArrow mBtnLeft;
mBtnUp = (ButtonArrow)findViewById(R.id.button_arrow_up);
mBtnUp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.e("action", "++ action down ++");
v.setBackgroundColor(0xff7f7f7f);
Intent intent = new Intent(ACTION_SEND_COMMAND);
intent.putExtra("CONTENT_TO_SEND", "u");
sendBroadcast(intent);
break;
case MotionEvent.ACTION_UP:
Log.e("action", "++ action up ++");
v.setBackgroundColor(0x007f7f7f);
Intent intent1 = new Intent(ACTION_SEND_COMMAND);
intent1.putExtra("CONTENT_TO_SEND", "e");
sendBroadcast(intent1);
break;
}
return false;
}
});
当然,别忘了将图片资源放在 /res/drawable 文件夹下面。