RemoteView addView无法正常工作

Ton*_* G. 9 android android-widget remoteview android-remoteview

我有一个应用程序小部件,我想添加视图(TextView等等),RemoteView但它永远不会出现.
这里是代码:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout);
    newView.setTextViewText(R.id.textUser, "1234");
    views.addView(views.getLayoutId(), newView);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?


这就是我最终做的事情:

RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout);
    newView.setTextViewText(R.id.textUser, "1234");
ComponentName thisWidget = new ComponentName(this,WidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
    manager.updateAppWidget(thisWidget, newView);
Run Code Online (Sandbox Code Playgroud)

Ros*_*ick 26

addView()方法需要要添加此新视图的布局内的视图的id,而不是布局本身.

而不是这个:

views.addView(views.getLayoutId(), newView);
Run Code Online (Sandbox Code Playgroud)

试试这个:

views.addView(R.id.view_container, newView);
Run Code Online (Sandbox Code Playgroud)

假设你的布局看起来像这样:

file:layout/widget_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/view_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <!-- New views will be added here at runtime -->
    </LinearLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • @Izkata 那是正确的。我只是这样布置它,因为我假设您将添加到整体布局中的特定容器。但这绝对不是必需的。 (2认同)