-1

我找到了这个代码来创建一个电池小部件:

public class BatteryStatusWidgetActivity extends AppWidgetProvider {  
   /** Called when the activity is first created. */  
      private String batteryLevel = "init";  
      private int widgetImageFrame = R.drawable.widget_batt_frame01;  
      @Override  
      public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
           context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));  
           updateView(context);  
      }  
      @Override  
      public void onReceive(Context context, Intent intent) {  
           int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);  
           int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);  
           int level = 65;  
           level = (rawlevel * 100) / scale;  
           String batteryLevel = level + "%";  
           widgetImageFrame = R.drawable.widget_batt_frame01;  
           updateView(context);  
           super.onReceive(context, intent);  
      }  
      public void updateView(Context context) {  
           RemoteViews thisViews = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.widget_layout);  
           thisViews.setTextViewText(R.id.widget_text, batteryLevel);  
           thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);  
           ComponentName thisWidget = new ComponentName(context, BatteryStatusWidgetActivity.class);  
           AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, thisViews);  
      }

这将仅在小部件中显示电池电量的数量。我的意思是“65”,我想显示“65%”。但是如果我尝试写一些batteryLevel = Integer.toString(level+"%");我得到错误的东西..我该怎么做?

4

4 回答 4

2
int level = 65;
String batteryLevel = level + "%";
于 2013-07-19T14:21:04.353 回答
2

试试这个它会工作

int level= 65;
String batterylevel = String.valueOf(level)+"%";

于 2013-07-19T14:32:54.293 回答
1

只需将您的代码替换onReceive()为以下内容,

 @Override  
      public void onReceive(Context context, Intent intent) {  
           int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);  
           int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);  
           int level = -1;  
           level = (rawlevel * 100) / scale;  
           batteryLevel = level+"%"; 
           widgetImageFrame = R.drawable.widget_batt_frame01;  
           updateView(context);  
           super.onReceive(context, intent);  
      } 

您收到错误的基本原因Integer.toString(level+"%")Integer.toString()此处使用的方法接受int值但不接受String值。level+"%"是一个字符串值

于 2013-07-19T14:34:36.923 回答
0

将其更改为:

int level = -1
level = (rawlevel * 100) / scale;  
String batteryLevel = level + "%";  
于 2013-07-19T14:34:37.993 回答