带有GridLayout项目的RecyclerView动态添加

时间:2016-02-04 18:07:55

标签: android android-recyclerview items

我的RecyclerView包含具有以下布局的项目:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"/>

    <View style="@style/Divider"/>

    <GridLayout
        android:id="@+id/grid_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

  </LinearLayout>

GridLayout可能包含1个或更多(30)个视图取决于recyclerview项目。 目前,在onBindViewHolder(recyclerview适配器)中,我动态添加了GridLayout中的视图。

我如何改善表现?除此之外,第一项不会显示在GridLayout中添加的视图,但在滚动后它们会出现。

谢谢。

public static class MyAdapter extends RecyclerView.Adapter<MyAdapter.CustomiewHolder> {

    private Context mContext;
    private List<Items> mItems;

    public MyAdapter(Context context, List<Items> items) {
        this.mContext = context;
        this.mItems = items;
    }

    @Override
    public CustomiewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.item_card, parent, false);

        return new CustomiewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CustomiewHolder holder, int position) {
        Item item = mItems.get(position);
        holder.mName.setText(item.getName());

        holder.mGridLayout.removeAllViews();
        holder.mGridLayout.setColumnCount(COLUMN_COUNT);

        for (int i = 0; i < item.getTiles().getItemCount(); i++) {
            View child = getView(holder.mRootLayout, item.getTiles().get(i));
            holder.mGridLayout.addView(child);
        }
    }

    public View getView(ViewGroup parent, Tile tile) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tile_card, parent, false);

        ((TextView) view.findViewById(R.id.tile_name)).setText(tile.getName());
        view.findViewById(R.id.line).setBackgroundResource(tile.getType().getDrawableResId());
        return view;
    }

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

    public static class CustomiewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.root_layout)
        public CardView mRootLayout;
        @Bind(R.id.station_name)
        public TextView mName;
        @Bind(R.id.routes_layout)
        public GridLayout mGridLayout;

        public CustomiewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

0 个答案:

没有答案