SORU
7 EKİM 2014, Salı


Nasıl çoklu görünüm türü ile RecyclerView oluşturmak için?

https://developer.android.com/preview/material/ui-widgets.html

ViewHolder belirtmek zorundayız RecyclerView.Adapter Biz oluştururken bu adaptörü bağlanacaktır.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private String[] mDataset;

    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;
        public ViewHolder(TextView v) {
            super(v);
            mTextView = v;
        }
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.some_layout, parent, false);

        //findViewById...

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mTextView.setText(mDataset[position]);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

Çoklu görünüm türü ile RecyclerView yaratmak mümkün değil mi?

CEVAP
7 EKİM 2014, Salı


Evet, bu mümkün. Sadece getItemViewType(), uygulamak ve onCreateViewHolder() viewType parametre ilgilen.

Şöyle yap:

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    class ViewHolder0 extends RecyclerView.ViewHolder {
        ...
    }

    class ViewHolder2 extends RecyclerView.ViewHolder {
        ...
    }

    @Override
    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be contiguous
        return position % 2 * 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         switch (viewType) {
             case 0: return new ViewHolder0(...);
             case 2: return new ViewHolder2(...);
             ...
         }
    }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ★TheCrono Official Channel★

    ★TheCrono

    3 Mayıs 2014
  • MW Technology

    MW Technolog

    28 EKİM 2009
  • Phymec

    Phymec

    18 Temmuz 2009