Android开发Tips
我们在开发Android应用的时候经常会遇到一些小问题,为了不让这些小问题浪费你的时间,最好还是记录下,毕竟Time is money.
下面是我遇到的一些简单的问题,我会持续更新,算是一些Tips:
给view的background设置selector不生效,因为selector的匹配规则是从上而下,所以我们应把state_pressed和state_selected等属性为ture的情况放在最前面,如果没有给view设置OnClickListener的话一定要给view设置clickable属性为true
1
2
3
4
5
6<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_all_selected" android:state_selected="true"/>
<item android:drawable="@drawable/ic_all_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/ic_all_unselected"/>
</selector>给TextView或者EditText设置setCompoundDrawables时,记得给Drawable对象setBounds
1
2
3final Drawable drawable = getResources().getDrawable(R.drawable.ic_add);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
textview.setCompoundDrawables(drawable, drawable, drawable, drawable);当View的maxWidth和maxHeight属性不生效时,不妨试试设置adjustViewBounds的属性为true
1
2
3
4
5
6
7<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="100dp"
android:maxHeight="100dp"
android:adjustViewBounds="true"/>当我们用Fragment嵌套Fragment时,同时Fragment又搭配ViewPager显示内容,会出现内层的Fragment的ViewPager不显示UI或者只显示第一页的问题,其实是因为Activity嵌套Fragment使用ViewPager时应该用getSupportFragmentManager()作为PagerAdapter实例化的参数,而当Fragment嵌套Fragment使用ViewPager时应该用getChildFragmentManager()
1
2MyPagerAdapter adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());//❌错误
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());//✔️正确当设计同学给的透明度标注是百分比而不是16进制的时候,总要自己去手动算,所以我找了下表一一对应
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00