“无法添加小部件”在Fragment中

我在添加Fragment中的小部件时遇到问题。 这里是一些硬编码添加3个示例小部件:

@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){//膨胀此片段的布局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中这样做时,一切正常。 我应该怎么做才能使它在碎片中工作?

在这里输入图像描述

链接地址: http://www.djcxy.com/p/81415.html

上一篇: "Couldn't add widget" in Fragment

下一篇: How to retrieve image in a gridview from fragment?