我的小部件是电池电量小部件。我想要的是根据电池电量显示不同的电池图像。这可以从我的代码中获得吗?
BatteryStatusWidgetActivity
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;
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);
}
和 widget_layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/widget_batt_frame01" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="10dip"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingTop="0dip" >
<TextView
android:id="@+id/widget_text"
style="@android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:text="@string/battery_level"
android:textSize="12dp"
android:textColor="#000000"/>
</LinearLayout>
</RelativeLayout>
谢谢你。