自定义控件玩套路以及canvas StaticLayout的使用

本文介绍了自定义控件的开发思路,包括如何在布局中使用和处理点击事件。通过实例展示了如何利用Canvas进行动画效果,如点击后出现晃动小手。同时详细解释了StaticLayout的构造参数及其在TextView中的应用,以及如何获取控件的准确尺寸。文章还探讨了Canvas的基本绘图元素和保存回滚操作,帮助读者深入理解Android自定义视图的开发。
摘要由CSDN通过智能技术生成

遇到自定义控件的时候很苦恼、不知道从哪里下手、鄙人也是新手、记录下开发的思路
我们有时候需要把某一个功能封装成控件、很简单、写好布局、将其inflate出来
必要的属性、就跟普通的activity一样定义即可、context直接调用getContext();

public class DanmakuChannel extends RelativeLayout {
   

    public boolean isRunning = false;
    public DanmakuEntity mEntity;
    private DanmakuActionInter danAction;

    public DanmakuActionInter getDanAction() {
        return danAction;
    }

    public void setDanAction(DanmakuActionInter danAction) {
        this.danAction = danAction;
    }

    public DanmakuChannel(Context context) {
        super(context);
        init();
    }


    public DanmakuChannel(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DanmakuChannel(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DanmakuChannel(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        inflater.inflate(R.layout.danmaku_channel_layout, null);
    }

}

定义完了、在布局中调用即可

<com.just.sun.widget.danmu.DanmuBase.DanmakuChannel
            android:id="@+id/danA"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_marginTop="10dp" />

要处理点击事件、很简单、可以findViewById setOnclickListener、跟Activity是一样的、
如果更麻烦一点要捕获触摸事件、需要重写方法
下面我通过点击做了个小动画、点击屏幕会出现晃动的小手、然后消失

    public View.OnTouchListener onLightTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (model.liveEntity != null) {
                float x = event.getX();
                float y = event.getY();
                final int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_DOWN://单点触摸动作
                       
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值