1

我创建了一个 android 小部件,当我添加一个配置活动时,小部件启动一种活动并关闭它,但小部件不显示,这显然是我的配置类中的代码有问题:

package com.rb.widget;

import android.app.Activity;
import android.os.Bundle;

public class WidgetConfig extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }



}

配置类应该是什么样子?

4

2 回答 2

1

这是因为配置活动必须返回一个值。

于 2013-09-23T16:06:53.497 回答
1

onCreate函数中,您应该调用

/**
 * In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
 * then we should not add app widget.
 */
setResult(RESULT_CANCELED);

以确保如果您关闭配置活动,小部件不会添加到主页。以下代码显示了如何配置小部件。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /**
     * In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
     * then we should not add app widget.
     */
    setResult(RESULT_CANCELED);

    setContentView(R.layout.activity_widget_settings);

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null){
        appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
        finish();
        return;
    }
    appWidgetManager = AppWidgetManager.getInstance(this);
    views = new RemoteViews(this.getPackageName(), R.layout.my_app_widget);
}

配置后,不要忘记调用:

Intent widgetIntent = new Intent();
widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK,widgetIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
于 2016-05-01T05:59:50.377 回答