這種感覺很通用
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 獲取寬-測量規(guī)則的模式和大小
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
// 獲取高-測量規(guī)則的模式和大小
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
/** 設(shè)置wrap_content的默認寬 / 高值 默認寬/高的設(shè)定并無固定依據(jù),根據(jù)需要靈活設(shè)置
*類似TextView,ImageView等針對wrap_content均在onMeasure()對設(shè)置默認寬 / 高值有特殊處理,
*具體讀者可以自行查看 */
int mWidth = 400;
int mHeight = 400;
// 當模式是AT_MOST(即wrap_content)時設(shè)置默認值
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mWidth, mHeight);
// 寬 / 高任意一個模式為AT_MOST(即wrap_content)時挽牢,都設(shè)置默認值
} else if (widthMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mWidth, heightSize);
} else if (heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSize, mHeight);
}