如何使用AppWidgetHostViews填充RecyclerView?

时间:2017-07-10 12:25:50

标签: android android-recyclerview android-viewholder

我正在尝试用AppWidgetHostViews填充RecyclerView,但我不确定如何做到这一点。我发现了一种创建LinearLayout的方法,将其强制转换为ViewGroup并调用viewList.add(hostView)。我想创建RecyclerView,这是我尝试的方式:

这是我的xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<View
    android:id="@+id/appWidget"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

这是我的适配器:

public class AppWidgetAdapter extends RecyclerView.Adapter<AppWidgetAdapter.AppWidgetHolder> {

private List<View> viewList = new ArrayList<>();

public void setData(List<View> list) {
    viewList.clear();
    viewList.addAll(list);
    notifyDataSetChanged();
}

@Override
public AppWidgetHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_widget_layout, parent, false);
    return new AppWidgetHolder(view);
}

@Override
public void onBindViewHolder(AppWidgetHolder holder, int position) {
    View view = getItem(position);
    holder.setView(view);
}

private View getItem(int position) {
    return !viewList.isEmpty() ? viewList.get(position) : null;
}

@Override
public int getItemCount() {
    return viewList.size();
}

class AppWidgetHolder extends RecyclerView.ViewHolder {

    private View view;

    AppWidgetHolder(View itemView) {
        super(itemView);
        view = (View) itemView.findViewById(R.id.app_widget);
    }

    private void setView (View view) {
        // ?
    }

}

}

在我的片段中:

private List<View> viewList = new ArrayList<>();

mAdapter = new AppWidgetAdapter();
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
viewList.add((View) event.eventObject);
mAdapter.setData(viewList);

事件对象是AppWidgetHostView ..我不知道如何在onBindViewHolder()方法中将它强制转换为绑定...在View对象中是否有一个方法我可以调用它来传递AppWidgetHostView,就像ViewGroup已添加一样() 方法?

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,也许它不是最好的方式,但它确实有效..

我用XML替换了View with FrameLayout,并更改了我的ViewHolder:

  class AppWidgetHolder extends RecyclerView.ViewHolder {

    private FrameLayout view;

    AppWidgetHolder(View itemView) {
        super(itemView);
        view = (FrameLayout) itemView.findViewById(R.id.app_widget);
    }

    private void setView (View view) {
        if(view.getParent() != null) {
            ((ViewGroup)view.getParent()).removeView(view);
        }
        this.view.addView(view);
    }

}