2017-07-11 38 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>