Android 开发中的一些小坑

说明

分享开发过程中遇到的一些问题,无关难度

selector

需求

给button一个黑色背景,点击时替换成灰色。
代码如下:

1
2
3
4
5
6
7
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click me"
android:textColor="@android:color/white"
android:background="@drawable/btn_bg"
/>

btn_bg.xml

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/black"/>
<item android:drawable="@android:color/gray" android:state_pressed="true"/>
</selector>

运行,点击按钮背景色都是黑色没有改变。

修改 btn_bg.xml 文件为:

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/gray" android:state_pressed="true"/>
<item android:drawable="@android:color/black"/>
</selector>

运行,点击按钮,一切正常。(其实把默认背景色放在最后一行即可,具体原因没有深究…)

notification

需求

显示一个通知。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
Notification notification = new NotificationCompat.Builder(getBaseContext())
.setTicker("呼叫消息")
.setContentTitle("呼叫消息")
.setContentText("this is a test message")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, mNotification);

运行,有声音提示,但是看不见通知栏。
修改:

1
2
3
4
5
6
7
8
9
10
11
12
Notification notification = new NotificationCompat.Builder(getBaseContext())
.setTicker("呼叫消息")
.setContentTitle("呼叫消息")
.setContentText("this is a test message")
.setSmallIcon(R.drawable.ic_launcher)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, mNotification);

运行,一些正常。(加入icon图片即可,具体原因没有深究…)


Waiting for the update …