10

我为 Android 应用程序创建小部件(当然是在 Java 中)。我有从布局创建的经典 RemoteViews(使用布局 ID)

RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.view);

我需要编辑或更改视图(通过 id 识别)。在经典视图中很容易,使用 findViewById 函数。

View v = ... //inflate layout R.layout.view
View my = v.findViewById(R.id.myViewId);
processView(my); //filling view

但它在 RemoteViews 中不受支持。可以使用 apply() 获取视图,但是在 processView 和 reapply() 之后我看不到视图的变化。

View v = rv.apply(context, null);
View my = v.findViewById(R.id.myViewId);
processView(my); //this work's fine
rv.reapply(context,my);

其次,更糟糕的选择是从 RemoteViews 获取我需要的视图,处理它,删除旧视图并使用 addView() 添加处理后的新视图。

RemoteViews rv = ...
View my = ... //apply, find and process
//remove old view
RemoteViews rvMy = ... //create RemoteViews from View
rv.addView(rvMy)

但我不知道如何从 View 创建 RemoteViews(有可能吗?)。任何想法如何解决这个问题?

4

2 回答 2

6

试试这种方式:

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget);

        remoteViews.setTextViewText(R.id.widget_textview, text); <---- here you can set text

        // Tell the widget manager
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

这是了解小部件行为的有用帖子:

http://www.vogella.com/articles/AndroidWidgets/article.html

于 2013-11-10T01:20:20.903 回答
1

因为从 removeview 编辑/更改(子)视图或从视图创建远程视图可能是不可能的(基于我创建的基本信息)我使用命名必要视图(大多数是 textview)解决了我的问题,使用他的名字和反射获取视图 ID 和循环中的过程。命名可以使用 bash、python 或其他任何东西。

例子:

RemoteView rv = ...

/* 
exemplary rv layout:
+-----+-----+-----+-----+-----+-----+
|tv0x0|tv0x1|tv0x2|tv0x3|tv0x4|tv0x5|
+-----+-----+-----+-----+-----+-----+
|tv1x0|tv1x1|tv1x2|tv1x3|tv1x4|tv1x5|
+-----+-----+-----+-----+-----+-----+
*/

String prefix = "tv";
for(int i=0; i<2;i++)
{
    for(int j=0; j<6; j++)
    {
        // use reflection, searched in stackoverflow
        int id = getItemIdFromName(prefix+i+"x"+j); 
        // working with concrete id using RemoteView set functions, e.g
        rv.setTextViewText(id, String.ValueOf(i);
    }
}

这种方式可以处理大量视图并为它们应用远程视图功能。

于 2013-11-14T20:18:34.303 回答