【问题标题】:How to use RemoteViews' addView() appropriately如何正确使用 RemoteViews 的 addView()
【发布时间】:2017-07-11 15:40:09
【问题描述】:

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

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

【问题讨论】:

    标签: android remoteview


    【解决方案1】:

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

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

    我的onUpdate() 专用于 Samsung Look 的 Edge Panel 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>
    

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多