如何定义自己的控件

以定义一个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 文件夹下面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值