单击 AlertDialog 项目列表时,在 RecyclerView 布局之间切换 [英] Switch between RecyclerView layouts when click on AlertDialog item list

查看:38
本文介绍了单击 AlertDialog 项目列表时,在 RecyclerView 布局之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三种不同的布局 cardsListLayout , titleLayout , cardMagazineLayout 将来可能会有更多,用作 onCreateViewHolder 方法.

我想在 onCreateViewHolder 方法中的视图之间切换,以便当用户从 AlertDialog 列表中选择时

这个 onOptionsItemSelected in MainActivity 那里有菜单项改变布局",这样当用户按下它时它就会出现 AlertDialog 列表

 @Override公共布尔 onOptionsItemSelected(MenuItem item) {if (item.getItemId() == R.id.change_layout) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle(getString(R.string.choose_layout));String[] layouts = {"Title Layout", "Cards List", "Card Magazine Layout"};builder.setItems(layouts, new DialogInterface.OnClickListener() {@覆盖public void onClick(DialogInterface dialog, int index) {开关(索引){case 0://标题布局Toast.makeText(MainActivity.this,"标题布局", Toast.LENGTH_LONG).show();休息;case 1://卡片列表Toast.makeText(MainActivity.this,"卡片列表", Toast.LENGTH_LONG).show();休息;案例2://卡片杂志布局Toast.makeText(MainActivity.this,"卡片杂志布局", Toast.LENGTH_LONG).show();}}});

这是我的自定义适配器类 PostAdapter

public class PostAdapter extends RecyclerView.Adapter{私有上下文上下文;私人列表<项目>项目;public PostAdapter(上下文上下文,列表<项目>项目){this.context = 上下文;this.items = 物品;}@非空@覆盖public PostAdapter.PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {LayoutInflater inflater = LayoutInflater.from(context);//这是我无法在它们之间切换的三种布局查看cardsListLayout = inflater.inflate(R.layout.post_item_card_layout, parent, false);查看 titleLayout = inflater.inflate(R.layout.post_item_grid_layout, parent, false);查看 cardMagazineLayout = inflater.inflate(R.layout.card_magazine_layout,parent,false);返回新的 PostViewHolder(titleLayout);}@覆盖public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {最终项目 item = items.get(position);holder.postTitle.setText(item.getTitle());最终文档文档 = Jsoup.parse(item.getContent());Elements elements = document.select("img");Log.e("CODE", "图片:" + elements.get(0).attr("src"));//Log.d("Text",document.text());//holder.postDescription.setText(document.text());Glide.with(context).load(elements.get(0).attr("src")).into(holder.postImage);holder.itemView.setOnClickListener(new View.OnClickListener() {@覆盖公共无效onClick(查看视图){意图意图=新意图(上下文,DetailsActivity.class);intent.putExtra("url", item.getUrl());intent.putExtra("title", item.getTitle());intent.putExtra("content", item.getContent());int youtubeThumbnailImagesetVisibility = 0;元素 element = document.body();String youtubeThumbnailImageSrc = "";String youTubeLink = "";for (元素 e : element.getElementsByClass(YOUTUBE-iframe-video")){youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");youTubeLink = e.attr("src");Log.e("YouTube 缩略图", youtubeThumbnailImageSrc);Log.e("Youtube 链接", youTubeLink);}如果 (youtubeThumbnailImageSrc.isEmpty()) {youtubeThumbnailImagesetVisibility = 8;intent.putExtra("youtubeThumbnailImagesetVisibility",youtubeThumbnailImagesetVisibility);} 别的 {intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);intent.putExtra("youTubeLink", youTubeLink);}//String imageSrc = elements.get(0).attr("src");//intent.putExtra("blogImage",imageSrc);context.startActivity(意图);}});}@覆盖公共 int getItemCount() {返回 items.size();}公共类 PostViewHolder 扩展 RecyclerView.ViewHolder {ImageView postImage;TextView 帖子标题;TextView postDescription;公共 PostViewHolder(查看 itemView){超级(项目视图);postImage = itemView.findViewById(R.id.postImage);postTitle = itemView.findViewById(R.id.postTitle);postDescription = itemView.findViewById(R.id.postDescription);}}}

我为每一个创建了两个不同的布局管理器,一个是 LinearLayoutManager 和一个 GridLayoutManager,目前我使用的是 GridLayout 所以我暂时评论了 LinearLayoutManger,直到我知道如何在它们之间切换

//linearLayoutManager = new LinearLayoutManager(this);gridLayoutManager = new GridLayoutManager(this, 2, RecyclerView.VERTICAL, false);//recyclerView.setLayoutManager(linearLayoutManager);recyclerView.setLayoutManager(gridLayoutManager);

我渴望的结果

解决方案

不需要为此使用多个Recyclerview

您可以使用单个 RecyclerviewMultiple viewType

来实现这一点

当你想改变Recyclerview的布局时,只需改变你的RecyclerviewLayoutManagerviewType就可以了会工作

示例代码

试试这个方法

首先为您的多视图类型创建一个三布局

<块引用>

网格布局

<相对布局android:layout_width="match_parent"android:layout_height="wrap_content"机器人:方向=垂直"><图像视图android:layout_width="match_parent"android:layout_height="150dp"android:adjustViewBounds="true"android:contentDescription="@string/app_name"android:scaleType="centerCrop"android:src="@drawable/dishu"/><文本视图android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"机器人:背景=#6a000000"机器人:重力=中心"机器人:填充=10dp"机器人:文本=虚拟文本"android:textColor="@android:color/white"/></RelativeLayout></android.support.v7.widget.CardView>

<块引用>

cardlist_layout

<线性布局android:layout_width="match_parent"android:layout_height="wrap_content"机器人:layout_gravity="中心"机器人:方向=垂直"><图像视图android:layout_width="match_parent"android:layout_height="150dp"android:adjustViewBounds="true"android:contentDescription="@string/app_name"android:scaleType="centerCrop"android:src="@drawable/dishu"/><文本视图android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingStart="5dp"android:paddingEnd="10dp"android:text="虚拟标题"android:textColor="@android:color/black"android:textStyle="粗体"/><文本视图android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingStart="5dp"android:paddingEnd="10dp"android:text="Dummy Tex"/></LinearLayout></android.support.v7.widget.CardView>

<块引用>

title_layout

<线性布局android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="中心"><线性布局android:layout_width="0dp"android:layout_height="wrap_content"机器人:layout_weight="1"机器人:方向=垂直"><文本视图android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingStart="5dp"android:paddingEnd="5dp"机器人:文本=虚拟文本"android:textColor="@android:color/black"android:textStyle="粗体"/><文本视图android:layout_width="match_parent"android:layout_height="wrap_content"机器人:重力=开始"android:paddingStart="5dp"android:paddingEnd="5dp"android:text="我有三种不同的布局 cardListLayout , titleLayout , cardMagazineLayout 并且将来可能会有更多,用作 onCreateViewHolder 方法的视图./></LinearLayout><图像视图android:layout_width="wrap_content"android:layout_height="150dp"android:adjustViewBounds="true"android:contentDescription="@string/app_name"android:scaleType="centerCrop"android:src="@drawable/dishu"/></LinearLayout></android.support.v7.widget.CardView>

<块引用>

数据适配器

包 neel.com.recyclerviewdemo;导入 android.content.Context;导入 android.support.annotation.NonNull;导入 android.support.v7.widget.RecyclerView;导入 android.view.LayoutInflater;导入 android.view.View;导入 android.view.ViewGroup;公共类 DataAdapter 扩展 RecyclerView.Adapter{public static final int ITEM_TYPE_GRID = 0;public static final int ITEM_TYPE_CARD_LIST = 1;public static final int ITEM_TYPE_TITLE_LIST = 2;私有上下文 mContext;私有 int VIEW_TYPE = 0;公共数据适配器(上下文 mContext){this.mContext = mContext;}公共无效 setVIEW_TYPE(int viewType) {VIEW_TYPE = 视图类型;notifyDataSetChanged();}@非空@覆盖public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {查看视图 = null;//在这里检查 viewType 并根据视图类型返回 RecyclerView.ViewHolder开关(VIEW_TYPE){案例ITEM_TYPE_GRID://如果 VIEW_TYPE 是 Grid 则返回 GridViewHolder视图 = LayoutInflater.from(mContext).inflate(R.layout.grid_layout, parent, false);返回新的 GridViewHolder(视图);案例 ITEM_TYPE_CARD_LIST://如果 VIEW_TYPE 是 Card List 则返回 CardListViewHolder视图 = LayoutInflater.from(mContext).inflate(R.layout.cardlist_layout, parent, false);返回新的 CardListViewHolder(view);案例 ITEM_TYPE_TITLE_LIST://如果 VIEW_TYPE 是 Title List 则返回 TitleListViewHolder视图 = LayoutInflater.from(mContext).inflate(R.layout.title_layout, parent, false);返回新的 TitleListViewHolder(view);}返回新的 GridViewHolder(视图);}@覆盖public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {final int itemType = getItemViewType(position);//首先在这里检查视图类型//将基于视图类型的数据设置为您的回收视图项目如果(itemType == ITEM_TYPE_GRID){if (holder instanceof CardViewHolder) {GridViewHolder viewHolder = (GridViewHolder) 持有人;//在此处为您的网格列表编写代码}} else if (itemType == ITEM_TYPE_CARD_LIST) {if (holder instanceof CardViewHolder) {CardListViewHolder buttonViewHolder = (CardListViewHolder) 持有人;//在此处为您的网格列表编写代码}} else if (itemType == ITEM_TYPE_TITLE_LIST) {if (holder instanceof CardViewHolder) {TitleListViewHolder buttonViewHolder = (TitleListViewHolder) 持有者;//在此处为 TitleListViewHolder 编写代码}}}@覆盖公共 int getItemCount() {返回 40;}//gridLayoutManager 的 RecyclerView.ViewHolder 类公共类 GridViewHolder 扩展 RecyclerView.ViewHolder {公共 GridViewHolder(@NonNull View itemView) {超级(项目视图);}}//卡片列表视图的 RecyclerView.ViewHolder 类公共类 CardListViewHolder 扩展 RecyclerView.ViewHolder {public CardListViewHolder(@NonNull View itemView) {超级(项目视图);}}//标题列表视图的 RecyclerView.ViewHolder 类公共类 TitleListViewHolder 扩展 RecyclerView.ViewHolder {public TitleListViewHolder(@NonNull View itemView) {超级(项目视图);}}}

<块引用>

主活动

包 neel.com.recyclerviewdemo;导入 android.content.DialogInterface;导入 android.os.Bundle;导入 android.support.v7.app.AlertDialog;导入 android.support.v7.app.AppCompatActivity;导入 android.support.v7.widget.GridLayoutManager;导入 android.support.v7.widget.LinearLayoutManager;导入 android.support.v7.widget.RecyclerView;导入 android.view.Menu;导入 android.view.MenuInflater;导入 android.view.MenuItem;公共类 MainActivity 扩展 AppCompatActivity {数据适配器数据适配器;私人 RecyclerView myRecyclerView;私人 LinearLayoutManager linearLayoutManager;私人 GridLayoutManager gridLayoutManager;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myRecyclerView = findViewById(R.id.myRecyclerView);myRecyclerView.setHasFixedSize(true);linearLayoutManager = new LinearLayoutManager(this);gridLayoutManager = new GridLayoutManager(this, 3);myRecyclerView.setLayoutManager(gridLayoutManager);dataAdapter = new DataAdapter(this);myRecyclerView.setAdapter(dataAdapter);}@覆盖公共布尔 onCreateOptionsMenu(菜单菜单){MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.home_menu, menu);//返回 true 以便打开弹出菜单返回真;}@覆盖公共布尔 onOptionsItemSelected(MenuItem item) {if (item.getItemId() == R.id.action_dialog) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("请选择一个布局");String[] layouts = {"Title Layout", "Cards List", "Grid View"};builder.setItems(layouts, new DialogInterface.OnClickListener() {@覆盖public void onClick(DialogInterface dialog, int index) {开关(索引){case 0://标题布局dataAdapter.setVIEW_TYPE(2);myRecyclerView.setLayoutManager(linearLayoutManager);myRecyclerView.setAdapter(dataAdapter);休息;case 1://卡片列表dataAdapter.setVIEW_TYPE(1);myRecyclerView.setLayoutManager(linearLayoutManager);myRecyclerView.setAdapter(dataAdapter);休息;case 2://网格布局dataAdapter.setVIEW_TYPE(0);myRecyclerView.setLayoutManager(gridLayoutManager);myRecyclerView.setAdapter(dataAdapter);}}});builder.show();}返回 super.onOptionsItemSelected(item);}}

<块引用>

activity_main 布局

<android.support.v7.widget.RecyclerViewandroid:id="@+id/myRecyclerView"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout>

输出

https://youtu.be/L3slKTy2bzI

I have three different layouts cardsListLayout , titleLayout , cardMagazineLayoutand there may be more in the future, which used as a views on onCreateViewHolder method.

I want to switch between views in onCreateViewHolder method so when user choose from AlertDialog list

this onOptionsItemSelected in MainActivity Where there is menu Item "change the layout" so that when the user presses it it appears AlertDialog list

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.change_layout) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.choose_layout));

            String[] layouts = {"Title Layout", "Cards List", "Card Magazine Layout"};
            builder.setItems(layouts, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int index) {
                    switch (index) {
                        case 0: // Title layout
                            Toast.makeText(MainActivity.this,
                                    "Title layout", Toast.LENGTH_LONG).show();
                            break;
                        case 1: // Cards List
                            Toast.makeText(MainActivity.this,
                                    "Card list", Toast.LENGTH_LONG).show();
                            break;
                        case 2: // Cards Magazine Layout
                            Toast.makeText(MainActivity.this,
                                    "Card Magazine Layout", Toast.LENGTH_LONG).show();
                    }
                }
            });

and this my custom adapter class PostAdapter

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
    private Context context;
    private List<Item> items;

    public PostAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public PostAdapter.PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

// here's the three layouts that I can't switch between it

        View cardsListLayout = inflater.inflate(R.layout.post_item_card_layout, parent, false);
        View titleLayout = inflater.inflate(R.layout.post_item_grid_layout, parent, false);
        View cardMagazineLayout = inflater.inflate(R.layout.card_magazine_layout,parent,false);

        return new PostViewHolder(titleLayout);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        final Item item = items.get(position);
        holder.postTitle.setText(item.getTitle());
        final Document document = Jsoup.parse(item.getContent());
        Elements elements = document.select("img");


        Log.e("CODE", "Image: " + elements.get(0).attr("src"));
//        Log.d("Text",document.text());
//        holder.postDescription.setText(document.text());

        Glide.with(context).load(elements.get(0).attr("src"))
                .into(holder.postImage);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, DetailsActivity.class);
                intent.putExtra("url", item.getUrl());
                intent.putExtra("title", item.getTitle());
                intent.putExtra("content", item.getContent());
                int youtubeThumbnailImagesetVisibility = 0;

                Element element = document.body();

                String youtubeThumbnailImageSrc = "";
                String youTubeLink = "";
                for (Element e : element.getElementsByClass
                        ("YOUTUBE-iframe-video")) {
                    youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
                    youTubeLink = e.attr("src");
                    Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
                    Log.e("Youtube link", youTubeLink);
                }

                if (youtubeThumbnailImageSrc.isEmpty()) {
                    youtubeThumbnailImagesetVisibility = 8;
                    intent.putExtra("youtubeThumbnailImagesetVisibility",
                            youtubeThumbnailImagesetVisibility);
                } else {
                    intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
                    intent.putExtra("youTubeLink", youTubeLink);
                }

//             String imageSrc = elements.get(0).attr("src");
//             intent.putExtra("blogImage",imageSrc);

                context.startActivity(intent);
            }
        });

    }

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

    public class PostViewHolder extends RecyclerView.ViewHolder {

        ImageView postImage;
        TextView postTitle;
        TextView postDescription;

        public PostViewHolder(View itemView) {
            super(itemView);
            postImage = itemView.findViewById(R.id.postImage);
            postTitle = itemView.findViewById(R.id.postTitle);
            postDescription = itemView.findViewById(R.id.postDescription);

        }
    }

}

I created two different Layout Manager for each one, there's a LinearLayoutManager and GridLayoutManager, currently I used GridLayout so I commented the LinearLayoutManger temporarily until I know how to switch between them

//      linearLayoutManager = new LinearLayoutManager(this);
        gridLayoutManager = new GridLayoutManager(this, 2, RecyclerView.VERTICAL, false);
//        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setLayoutManager(gridLayoutManager);

The result I aspire to

解决方案

No need to use multiple Recyclerview for this

You can achieve this using single Recyclerview with Multiple viewType

When you want to change the layout of Recyclerview just change the LayoutManager and viewType of your Recyclerview it will work

SAMPLE CODE

Try this way

First Create a Three layout for your Multiple viewType

grid_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="150dp"
    android:layout_height="150dp"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true">

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

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="centerCrop"
            android:src="@drawable/dishu" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="#6a000000"
            android:gravity="center"
            android:padding="10dp"
            android:text="dummy text"
            android:textColor="@android:color/white" />
    </RelativeLayout>

</android.support.v7.widget.CardView>

cardlist_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true">

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

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="centerCrop"
            android:src="@drawable/dishu" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingStart="5dp"
            android:paddingEnd="10dp"
            android:text="Dummy Title"
            android:textColor="@android:color/black"
            android:textStyle="bold" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingStart="5dp"
            android:paddingEnd="10dp"
            android:text="Dummy Tex" />


    </LinearLayout>
</android.support.v7.widget.CardView>

title_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="10dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingStart="5dp"
                android:paddingEnd="5dp"
                android:text="dummy text"
                android:textColor="@android:color/black"
                android:textStyle="bold" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="start"
                android:paddingStart="5dp"
                android:paddingEnd="5dp"
                android:text="I have three different layouts cardsListLayout , titleLayout , cardMagazineLayoutand there may be more in the future, which used as a views on onCreateViewHolder method." />
        </LinearLayout>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="150dp"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="centerCrop"
            android:src="@drawable/dishu" />


    </LinearLayout>
</android.support.v7.widget.CardView>

DataAdapter

package neel.com.recyclerviewdemo;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

    public static final int ITEM_TYPE_GRID = 0;
    public static final int ITEM_TYPE_CARD_LIST = 1;
    public static final int ITEM_TYPE_TITLE_LIST = 2;
    private Context mContext;
    private int VIEW_TYPE = 0;

    public DataAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public void setVIEW_TYPE(int viewType) {
        VIEW_TYPE = viewType;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = null;
        // check here the viewType and return RecyclerView.ViewHolder based on view type
        switch (VIEW_TYPE) {
            case ITEM_TYPE_GRID:
                // if VIEW_TYPE is Grid than return GridViewHolder
                view = LayoutInflater.from(mContext).inflate(R.layout.grid_layout, parent, false);
                return new GridViewHolder(view);
            case ITEM_TYPE_CARD_LIST:
                // if VIEW_TYPE is Card List than return CardListViewHolder
                view = LayoutInflater.from(mContext).inflate(R.layout.cardlist_layout, parent, false);
                return new CardListViewHolder(view);
            case ITEM_TYPE_TITLE_LIST:
                // if VIEW_TYPE is Title List than return TitleListViewHolder
                view = LayoutInflater.from(mContext).inflate(R.layout.title_layout, parent, false);
                return new TitleListViewHolder(view);
        }
        return new GridViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final int itemType = getItemViewType(position);
        // First check here the View Type
        // than set data based on View Type to your recyclerview item
        if (itemType == ITEM_TYPE_GRID) {
        if (holder instanceof CardViewHolder) {
            GridViewHolder viewHolder = (GridViewHolder) holder;
            // write here code for your grid list
      }
        } else if (itemType == ITEM_TYPE_CARD_LIST) {
       if (holder instanceof CardViewHolder) {
            CardListViewHolder buttonViewHolder = (CardListViewHolder) holder;
            // write here code for your grid list
       }
        } else if (itemType == ITEM_TYPE_TITLE_LIST) {
            if (holder instanceof CardViewHolder) {
            TitleListViewHolder buttonViewHolder = (TitleListViewHolder) holder;
            // write here code for your TitleListViewHolder
          }
        }
    }

    @Override
    public int getItemCount() {
        return 40;
    }

    // RecyclerView.ViewHolder class for gridLayoutManager
    public class GridViewHolder extends RecyclerView.ViewHolder {

        public GridViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    // RecyclerView.ViewHolder class for Card list View
    public class CardListViewHolder extends RecyclerView.ViewHolder {

        public CardListViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    // RecyclerView.ViewHolder class for Title list View
    public class TitleListViewHolder extends RecyclerView.ViewHolder {

        public TitleListViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

MainActivity

package neel.com.recyclerviewdemo;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    DataAdapter dataAdapter;
    private RecyclerView myRecyclerView;
    private LinearLayoutManager linearLayoutManager;
    private GridLayoutManager gridLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myRecyclerView = findViewById(R.id.myRecyclerView);
        myRecyclerView.setHasFixedSize(true);

        linearLayoutManager = new LinearLayoutManager(this);
        gridLayoutManager = new GridLayoutManager(this, 3);

        myRecyclerView.setLayoutManager(gridLayoutManager);

        dataAdapter = new DataAdapter(this);
        myRecyclerView.setAdapter(dataAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home_menu, menu);
        // return true so that the menu pop up is opened
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_dialog) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Please choose a layout");

            String[] layouts = {"Title Layout", "Cards List", "Grid View"};
            builder.setItems(layouts, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int index) {
                    switch (index) {
                        case 0: // Title layout
                            dataAdapter.setVIEW_TYPE(2);
                            myRecyclerView.setLayoutManager(linearLayoutManager);
                            myRecyclerView.setAdapter(dataAdapter);
                            break;
                        case 1: // Cards List
                            dataAdapter.setVIEW_TYPE(1);
                            myRecyclerView.setLayoutManager(linearLayoutManager);
                            myRecyclerView.setAdapter(dataAdapter);
                            break;
                        case 2: // Grid  Layout
                            dataAdapter.setVIEW_TYPE(0);
                            myRecyclerView.setLayoutManager(gridLayoutManager);
                            myRecyclerView.setAdapter(dataAdapter);
                    }
                }
            });

            builder.show();
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

OUTPUT

https://youtu.be/L3slKTy2bzI

这篇关于单击 AlertDialog 项目列表时,在 RecyclerView 布局之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆