且听风吟

Don't panic! I'm a programmer.

利用level-list显示图片

| Comments

有时候,我们为了在一个ImageView中显示不同的图片,往往会使用:

if (条件1) {
    image.setBackground(R.id.xxx1);
} else if (条件2) {
    image.setBackground(R.id.xxx2);
} ...

可以用另一个简便的方法实现相同的功能。

首先,在res/drawable下建立一个xml文件,内容如下

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="4" android:drawable="@drawable/stat_sys_battery_0" />
    <item android:maxLevel="14" android:drawable="@drawable/stat_sys_battery_10" />
    <item android:maxLevel="29" android:drawable="@drawable/stat_sys_battery_20" />
    <item android:maxLevel="49" android:drawable="@drawable/stat_sys_battery_40" />
    <item android:maxLevel="69" android:drawable="@drawable/stat_sys_battery_60" />
    <item android:maxLevel="89" android:drawable="@drawable/stat_sys_battery_80" />
    <item android:maxLevel="100" android:drawable="@drawable/stat_sys_battery_100" />
</level-list>

然后在layout中把ImageView的src设置成已创建好的xml文件。 程序中需要更新图片时,只需要使用

imageview.getDrawable().setLevel(50)

Android会根据level的值自动选择对应的图片。显示剩余电量就是用这个方法来显示不同图片的。

WebView.clearHistory()的问题

| Comments

Q:

I call WebView.clearHistory(), but I am still able to go back after doing so. I want to reuse a WebView, but I don’t want the back button to allow the user to go back further than the current “session” of using the WebView. Anybody know what is the best way to handle this? I thought for sure that clearHistory() would do it.

A:

I recently had the same issue. What I found is that you have to clear history AFTER the (first) page loads. It appears that the history clears everything before the current page so if your browser is at page “A”, you clear history and navigate to page “B” your history will be “A” “B”, not just “B”, but if you clear history when “B” finishes loading you will have only “B”. In my case I end up using “onPageFinished” method of the WebViwClient, but in this case you have to know what your start page is and clear the history only after it otherwise you will be clearing the history after every page navigated after the first. Stefan