自定義組件及其內組件大小的正確設置
https://blog.csdn.net/xiaodao1986/article/details/8481288
一、自定義組件大小的設置
不管你怎麼設置,自定義組件似乎總是match_parent。我們需要覆蓋onMeasure方法,並在其內正確設置組件大小。
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- //注意:為盡可能簡潔本文隻討論EXACTLY和AT_MOST模式
- int mode = MeasureSpec.getMode(widthMeasureSpec);
- if(mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
- this.widthMeasureSpec = widthMeasureSpec;
- this.heightMeasureSpec = heightMeasureSpec;
- int width = MeasureSpec.getSize(widthMeasureSpec);
- int height = MeasureSpec.getSize(heightMeasureSpec);
- setMeasuredDimension(width, height);
- } else if(mode == MeasureSpec.UNSPECIFIED) {
- Log.d("WOGU", "mode=UNSPECIFIED");
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
- }
最後更新:2017-04-04 07:03:34