1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.titcktick.customview; import android.content.Context; import android.util.AttributeSet; import android.view.View; public class CustomView extends View { public CustomView(Context context) { super (context); } public CustomView(Context context, AttributeSet attrs) { super (context, attrs); } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { super .onMeasure(widthMeasureSpec, heightMeasureSpec); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <com.titcktick.customview.CustomView android:layout_width= "match_parent" android:layout_height= "match_parent" android:layout_margin= "10dp" android:background= "@android:color/black" /> </LinearLayout> |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
package com.titcktick.customview; import android.content.Context; import android.util.AttributeSet; import android.view.View; public class CustomView extends View { private static final int DEFAULT_VIEW_WIDTH = 100 ; private static final int DEFAULT_VIEW_HEIGHT = 100 ; public CustomView(Context context) { super (context); } public CustomView(Context context, AttributeSet attrs) { super (context, attrs); } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { int width = measureDimension(DEFAULT_VIEW_WIDTH, widthMeasureSpec); int height = measureDimension(DEFAULT_VIEW_HEIGHT, heightMeasureSpec); setMeasuredDimension(width, height); } protected int measureDimension( int defaultSize, int measureSpec ) { int result = defaultSize; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); //1. layout給出了確定的值,比如:100dp //2. layout使用的是match_parent,但父控件的size已經可以確定了,比如設置的是具體的值或者match_parent if (specMode == MeasureSpec.EXACTLY) { result = specSize; //建議:result直接使用確定值 } //1. layout使用的是wrap_content //2. layout使用的是match_parent,但父控件使用的是確定的值或者wrap_content else if (specMode == MeasureSpec.AT_MOST) { result = Math.min(defaultSize, specSize); //建議:result不能大於specSize } //UNSPECIFIED,沒有任何限制,所以可以設置任何大小 //多半出現在自定義的父控件的情況下,期望由自控件自行決定大小 else { result = defaultSize; } return result; } } |