关于自定义view中使用的getWidth()和geHeight()方法小结

    xiaoxiao2021-03-28  36

    1. 不需要设置wrap_content属性,对应布局中给特定高度或者match_parent,就不需要自己重写onMeasure方法(该方法中默认提供),getheight()和getwidth()得到的就是所属的自定义iew的宽度和高度,如下所示:

    1.1 /** * 注意:在自定义view中的如果不需要设置wrap_content属性就不需要自己重写onMeasure方法 * 因为在onMeasure方法中系统默认会自动测量两种模式:一个是match_parent另一个则是自己指定明确尺寸大小 * 这两种方法对应着这一种MeasureSpec.AT_MOST测量模式,由于我们设置这个自定义浮动的字母索引表宽度是指定明确大小 * 高度是match_parent模式,所以这里就不要手动测量了直接通过getHeightgetWidth直接拿到系统自动测量好高度和宽度 * */ int height = getHeight(); int width = getWidth(); 1.2对应布局中的写法(标红部分),<com.example.administrator.customcontacts.LetterListView android:id="@+id/id_letterview" android:layout_width="30dp" android:layout_height="match_parent" android:layout_alignParentRight="true" />

    2. 布局文件中高度和宽度是wrap_content情况下,需要重写onMeasure()方法,获取自己想要的高度和宽度,关键代码如下:

    2.1 //View默认最小宽度 private static final int DEFAULT_MIN_WIDTH = 300; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(measure(widthMeasureSpec),measure(heightMeasureSpec)); } private int measure(int origin) { int result = DEFAULT_MIN_WIDTH; int specMode = MeasureSpec.getMode(origin); int specSize = MeasureSpec.getSize(origin); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } 注:此时在需要的地方调用getHeight()和getWidth()方法得到的值:是在measure()方法中,默认大小 DEFAULT_MIN_WIDTH分别和MeasureSpec.EXACTLY,MeasureSpec.AT_MOST两种模式经过对比后所到的 2.2 对应布局中的写法(标红部分)<com.example.administrator.customrecordview.RecordView android:id="@+id/recordView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" />
    转载请注明原文地址: https://ju.6miu.com/read-664701.html

    最新回复(0)