1.自定义View的构造函数调用的场景
package com.sina.myapplication;import android.content.Context;
import android.util.AttributeSet;
import android.view.View;import androidx.annotation.Nullable;public class Textview extends View {//在new Textview类的时候调用public Textview(Context context) {super(context);}//在layout布局中使用public Textview(Context context, @Nullable AttributeSet attrs) {super(context, attrs);}//在layout布局中使用, 并且携带Stylepublic Textview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);//布局的宽高都是由此指定//指定控制的狂傲,需要测量//可以获取XML中设置的宽高的模式int widthMode = MeasureSpec.getMode(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);//在布局中指定了wrap_contentif (widthMode == MeasureSpec.AT_MOST);//在布局中获取一个确切的值,match_parent,fill_parentif(widthMode == MeasureSpec.EXACTLY);//在布局中尽可能大,ListView,ScrollView中会使用if(widthMode == MeasureSpec.UNSPECIFIED);}
}
2.ListView,ScrollView显示不全的解决方法。方案为重写onMeasure该方法。
package com.sina.myapplication;import android.content.Context;
import android.util.AttributeSet;
import android.view.View;import androidx.annotation.Nullable;public class MyListView extends View {public MyListView(Context context) {super(context);}public MyListView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);}public MyListView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);/*widthMeasureSpec,heightMeasureSpec:总计32位,会包含两个信息,1.值,30位,MAX_VALUE>>2。 2.模式,MeasureSpec.AT_MOST 2位。*/super.onMeasure(widthMeasureSpec, heightMeasureSpec);}
}