【问题标题】:Need help about a widget需要有关小部件的帮助
【发布时间】:2013-08-22 14:31:28
【问题描述】:

这是一个电池小部件。这不是我的代码,而是取自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,以此类推。

编辑:第一点解决了。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      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;
      }
      

      【讨论】:

      • 这是一个小部件..我不认为我可以使用findViewById
      猜你喜欢
      • 2011-10-08
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2016-11-24
      • 2015-06-23
      • 2014-12-26
      • 2013-08-12
      • 2014-06-11
      相关资源
      最近更新 更多