"无法添加小部件"在片段中

时间:2016-12-07 14:14:33

标签: android android-fragments widget fragment

我在Fragment中添加widget有问题。这是一些硬编码添加3示例小部件:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_widget, container, false);

    mainlayout = (ViewGroup) root.findViewById(R.id.main_layout);

    mAppWidgetManager = AppWidgetManager.getInstance(getContext());
    mAppWidgetHost = new AppWidgetHost(getContext(), R.id.APPWIDGET_HOST_ID);

    addButton = (Button) root.findViewById(R.id.bt_add);
    removeButton = (Button) root.findViewById(R.id.bt_remove);
    addButton.setOnClickListener(this);
    removeButton.setOnClickListener(this);

    AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(9);
    Log.e(TAG, "createWidget: " + Integer.toString(9) + appWidgetInfo);

    AppWidgetHostView hostView = mAppWidgetHost.createView(getActivity(), 9, appWidgetInfo);
    hostView.setAppWidget(9, appWidgetInfo);
    mainlayout.addView(hostView);

    appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(11);
    Log.e(TAG, "createWidget: " + Integer.toString(11) + appWidgetInfo);

    hostView = mAppWidgetHost.createView(getActivity(), 11, appWidgetInfo);
    hostView.setAppWidget(11, appWidgetInfo);
    mainlayout.addView(hostView);

    appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(10);
    Log.e(TAG, "createWidget: " + Integer.toString(10) + appWidgetInfo);

    hostView = mAppWidgetHost.createView(getActivity(), 10, appWidgetInfo);
    hostView.setAppWidget(10, appWidgetInfo);
    mainlayout.addView(hostView);

    mAppWidgetHost.startListening();
    return root;
}

首先是好的,第二个应该是天气小部件,但它只显示"无法添加小部件"最后一个没有加载电子邮件。

当我在Activity中执行此操作时,一切正常。我该怎么做才能让它在Fragment中运行?

enter image description here

0 个答案:

没有答案