2017-07-10 101 views
1

我想用AppWidgetHostViews填充RecyclerView,但我不確定如何做到這一點。我找到了創建LinearLayout的方法,將它轉換爲ViewGroup並調用viewList.add(hostView)。我想創建RecyclerView代替,這是我試過的方式:如何用AppWidgetHostViews填充RecyclerView?

這是我的xml:

這是我的適配器:

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

我找到了解決辦法,也許這是不是最好的方式,但它的工作原理..

我換成查看與FrameLayout裏中的XML,並改變了我的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); 
    } 

}