自定義 View 中 wrap_content 無效的解決方案
做過自定義 View 的童鞋都會發現,直接繼承 View 的自定義控件需要重寫 onMeasure() 方法,並設置 wrap_content 時的自身大小,否則在布局文件中對自定義控件在設置大小時,wrap_content 將等同於 match_parent。
其實在 Android 中自帶的控件中,也都對 onMeasure() 方法進行了重寫,對於 wrap_content 等情況做了特殊處理,在 wrap_content 時給出了默認的寬、高。所以對於這個問題的處理我們也就有了一定的思路,在 onMeasure() 中對於 wrap_content 情況給出合適的寬、高即可,代碼如下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heithtSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, 200);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, heithtSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize, 200);
}
}