2017-07-11 217 views
0

我见过其他答案,例如this onethis one,它们解释了将新View添加到RemoteViews对象的正确方法。在第一个链接中,指定在外部LinearLayout内部应该有嵌套的LinearLayout,以便在addView方法中引用内部布局,例如, addView(innerLayoutID, view)如何正确使用RemoteViews的addView()

为什么引用内部布局而不是外部布局? addView不适用于外部布局吗?或者这只是个人意见?

回答

0

事实证明,第一个链接的答案通常是正确的,但我无法完全按照发布的方式运行,所以我需要更多的细节才能让它在我的项目中运行。我在下面发布了我的代码以供将来参考。

请注意,其他线程中未指定的非常重要的是rv.addView()需要与rv对象中指定的布局相同;也就是说,我不能有嵌套在另一个LinearLayout中的LinearLayout,然后引用内部的LinearLayout。我不得不引用外部实例,因为那是父代rv实例中引用的内容。

onUpdate()是针对三星Look的边缘面板API,但一般格式是一样的:

@Override 
public void onUpdate(Context context, SlookCocktailManager manager, int[] cocktailIds) { 
    //Parent RemoteViews object 
    RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main_view); 
    for (int i = 0; i < someObjectArray.length; i++) { 
     //Create new remote view using the xml file that represents a list entry 
     RemoteViews listEntryLayout = new RemoteViews(context.getPackageName(), R.layout.list_entry); 
     //Set the text of the TextView that is inside the above specified listEntryLayout RemoteViews 
     listEntryLayout.setTextViewText(R.id.stock_text, someObjectArray[i].getName()); 
     //Add the new remote view to the parent/containing Layout object 
     rv.addView(R.id.main_layout, listEntryLayout); 
    } 
    //standard update 
    if (cocktailIds != null) { 
     for (int id : cocktailIds) { 
      manager.updateCocktail(id, rv); 
     } 
    } 
} 

main_view.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/main_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:importantForAccessibility="2" 
    android:orientation="vertical" > 
</LinearLayout> 

list_entry.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/stock_layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/stock_text" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:background="@android:color/holo_green_light" 
     android:text="TextView" 
     android:textSize="20dp"/> 
</LinearLayout>