自己定义View-2-重写onMeasure

本文介绍了一个自定义的Android View组件——FirstView,该组件通过重写onMeasure方法来自定义其尺寸测量逻辑。FirstView能够根据不同的MeasureSpec模式调整自身大小,并提供了一种简单的方法来实现自定义View的尺寸控制。

效果图

这里写图片描写叙述

布局文件

<?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"> <TextView android:layout_width="match_parent" android:layout_height="100dp" android:background="#003839" android:gravity="center" android:visibility="visible" android:text="SECOND"/> <com.pengkv.apple.weight.FirstView android:layout_width="wrap_content" android:visibility="visible" android:background="#888787" android:layout_height="wrap_content"/> </LinearLayout>

View代码

public class FirstView extends LinearLayout {

    public FirstView(Context context) {//代码实例化的时候调用
        super(context);
    }

    public FirstView(Context context, AttributeSet attrs) {//布局文件引用的时候调用
        super(context, attrs);
    }

    public FirstView(Context context, AttributeSet attrs, int defStyleAttr) {//自己定义属性值的时候调用
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        setMeasuredDimension(measureSpec(widthMeasureSpec),measureSpec(heightMeasureSpec)); //重測尺寸
    }

    public int measureSpec(int measureSpec){
        int result=0;
        int specMode=MeasureSpec.getMode(measureSpec);//获取測量模式
        int specSize=MeasureSpec.getSize(measureSpec);//获取測量尺寸

        if (specMode==MeasureSpec.EXACTLY){//精确模式:包含准确设置dp值和match_parent
            result=specSize;
        }else {
            result=400;//默认设置的尺寸
            if (specMode==MeasureSpec.AT_MOST){
                result=Math.min(result,specSize);
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值