需要有关小部件的帮助

时间:2013-08-22 14:31:28

标签: android android-layout android-widget android-appwidget batterylevel

这是一个电池小部件。这不是我的代码,而是来自http://www.cmwmobile.com/index.php?option=com_content&view=article&id=56&Itemid=68

private final BroadcastReceiver batteryChangedReceiver = new
                BroadcastReceiver() {
            /**
             * {@inheritDoc}
             */
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if (action != null && action.equals(
                        Intent.ACTION_BATTERY_CHANGED)) {
                    int rawLevel = intent.getIntExtra(
                        BatteryManager.EXTRA_LEVEL, -1);
                    int scale = intent.getIntExtra(
                        BatteryManager.EXTRA_SCALE, 1);

                    if (scale > 0) {
                        batteryLevel = rawLevel * 100 / scale;
                    }
                    else {
                        batteryLevel = rawLevel;
                    }

                    intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                    intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
                    intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);

                    updateBattery(context);
                }
                else if (action != null && action.equals(ACTION_UPDATE)) {
                    updateBattery(context);
                }
            }
        };

我需要改变的是两件事。

1)(已解决)我需要在电池电量后实现%符号,我不知道它是怎么做的。我试过了batteryLevel = rawLevel + "%";,但却给我一个错误。

2)实际上这个小部件只有背景颜色而不是图像..如果我将图像作为背景,除了在xml布局中更改背景之外怎么办?我的意思是以编程方式我希望在电池电量变化时更改图像。例如,如果电池电量为80则为img1,如果是70则为img2等等。

编辑:第一点解决了。

2 个答案:

答案 0 :(得分:1)

2)使用方法setImageResource(或setImageBitmap,... ImageView documentation

ImageView img = new ImageView(this);
img.setResource(R.drawable.image);

答案 1 :(得分:0)

2)如果你的.xml文件有例如LinearLayout,

LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
switch(batteryLevel){
case 80:
    layout.setBackgroundResource(R.drawable.image_for_80);
    break;
case 70:
    layout.setBackgroundResource(R.drawable.image_for_70);
    break;
}