使用RecyclerView和GridLayoutManager的简单Android网格示例(如旧的GridView) [英] Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

查看:176
本文介绍了使用RecyclerView和GridLayoutManager的简单Android网格示例(如旧的GridView)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 RecyclerView 取代了旧的 ListView GridView 。我正在寻找一个非常基本的示例,使用 RecyclerView 显示最小的网格设置。我不是在寻找漫长的教程风格解释,只是一个简单的例子。我想象一下模拟旧GridView的最简单的网格将包含以下功能:

$ ul

  • 每行多个单元格

  • 每个单元格中的单一视图
  • 响应点击事件

    解决方案

    下面是一个简单的例子,它看起来像下面的图片。





    从一个空的活动开始。您将执行以下任务来添加 RecyclerView 网格。您只需在每个部分复制并粘贴代码即可。




    • 添加依赖到gradle

    • 添加xml为活动和网格单元设置布局文件
    • 制作RecyclerView适配器

    • 在您的活动中初始化RecyclerView



    更新Gradle依赖关系



    确保以下依赖项在您的应用程序 gradle中。 build file:

      compile'c​​om.android.support:appcompat-v7:25.0.0' 
    compile'c​​om.android.support:recyclerview-v7:25.0.0'

    您可以将版本号更新为最新的



    创建活动布局



    在您的xml布局中添加 RecyclerView

    activity_main.xml

     <?xml version =1.0encoding = UTF-8 >?; 
    < RelativeLayout
    xmlns:android =http://schemas.android.com/apk/res/android
    android:layout_width =match_parent
    android:layout_height = match_parent >

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

    < / RelativeLayout>



    创建网格单元格布局



    在我们的 RecyclerView 网格中只有一个 TextView 。创建一个新的布局资源文件。

    recyclerview_item.xml
    $ b

     <?xml version =1.0encoding =utf-8?> 
    < LinearLayout
    xmlns:android =http://schemas.android.com/apk/res/android
    android:orientation =horizo​​ntal
    android:padding =5dp
    android:layout_width =50dp
    android:layout_height =50dp>

    TextView
    android:id =@ + id / info_text
    android:layout_width =match_parent
    android:layout_height =match_parent
    android:gravity =center
    android:background =@ color / colorAccent/>

    < / LinearLayout>



    创建适配器



    RecyclerView 需要一个适配器来将数据填充到每个单元格中的视图。创建一个新的java文件。

    MyRecyclerViewAdapter.java

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

    private String [] mData = new String [0];
    私人LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    //将数据传入构造函数
    MyRecyclerViewAdapter(Context context,String [] data){
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;
    }

    //在需要时从xml膨胀单元格布局
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
    View view = mInflater.inflate(R.layout.recyclerview_item,parent,false);
    返回新的ViewHolder(view);
    }

    //将数据绑定到每个单元格中的textview
    @Override
    public void onBindViewHolder(ViewHolder holder,int position){
    String animal = mData [position];
    holder.myTextView.setText(animal);
    }

    //单元总数
    @Override
    public int getItemCount(){
    return mData.length;



    //在屏幕滚动时存储和回收视图
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView myTextView;

    ViewHolder(查看itemView){
    super(itemView);
    myTextView =(TextView)itemView.findViewById(R.id.info_text);
    itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view){
    if(mClickListener!= null)mClickListener.onItemClick(view,getAdapterPosition());
    }
    }

    //在点击位置获取数据的便捷方法
    String getItem(int id){
    return mData [id];
    }

    //允许点击事件被捕获
    void setClickListener(ItemClickListener itemClickListener){
    this.mClickListener = itemClickListener;
    }

    //父活动将实现此方法来响应点击事件
    public interface ItemClickListener {
    void onItemClick(View view,int position);
    }
    }

    注意




    • 虽然不是绝对必要的,但我还包含了监听单元格上单击事件的功能。这在旧的 GridView 中是可用的,并且是常见的需求。您可以删除此代码,如果您不需要它。



    在活动中初始化RecyclerView



    将以下代码添加到您的主要活动中。



    MainActivity.java

      public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

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

    //数据用
    填充RecyclerView String [] data = {1,2,3,4,5,6, 7,8,9,10,11,12,13,14,15,16,17,18,19 ,20,21,22,23,24,25,26,27,28,29,30,31 32,33,34,35,36,37,38,39,40,41,42,43,44 ,45,46,47,48};

    //设置RecyclerView
    RecyclerView recyclerView =(RecyclerView)findViewById(R.id.rvNumbers);
    int numberOfColumns = 6;
    recyclerView.setLayoutManager(新的GridLayoutManager(this,numberOfColumns));
    adapter = new MyRecyclerViewAdapter(this,data);
    adapter.setClickListener(this);
    recyclerView.setAdapter(adapter);

    $ b @Override
    public void onItemClick(View view,int position){
    Log.i(TAG,您点击了数字+适配器。 getItem(位置)+,位于单元位置+位置);
    }
    }

    注意




    • 请注意,该活动实现了我们在适配器中定义的 ItemClickListener 。这允许我们在 onItemClick 中处理单元格单击事件。


    完成

  • h1>

    就是这样。你应该能够现在运行你的项目,并获得类似于顶部图像的东西。



    继续



    圆角





    自动调整列





    进一步研究




    I know that RecyclerView has replaced the functionality of the old ListView and GridView. I am looking for a very basic example that shows a minimal grid setup using RecyclerView. I am not looking for long tutorial style explanations, just a minimal example. I imagine the simplest grid that mimics the old GridView would consist of the following features:

    • multiple cells per row
    • single view in each cell
    • responds to click events

    解决方案

    The following is a minimal example that will look like the image below.

    Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

    • Add dependencies to gradle
    • Add the xml layout files for the activity and for the grid cell
    • Make the RecyclerView adapter
    • Initialize the RecyclerView in your activity

    Update Gradle dependencies

    Make sure the following dependencies are in your app gradle.build file:

    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    

    You can update the version numbers to whatever is the most current.

    Create activity layout

    Add the RecyclerView to your xml layout.

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvNumbers"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </RelativeLayout>
    

    Create grid cell layout

    Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

    recyclerview_item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:padding="5dp"
        android:layout_width="50dp"
        android:layout_height="50dp">
    
            <TextView
                android:id="@+id/info_text"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:background="@color/colorAccent"/>
    
    </LinearLayout>
    

    Create the adapter

    The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

    MyRecyclerViewAdapter.java

    public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
    
        private String[] mData = new String[0];
        private LayoutInflater mInflater;
        private ItemClickListener mClickListener;
    
        // data is passed into the constructor
        MyRecyclerViewAdapter(Context context, String[] data) {
            this.mInflater = LayoutInflater.from(context);
            this.mData = data;
        }
    
        // inflates the cell layout from xml when needed
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
            return new ViewHolder(view);
        }
    
        // binds the data to the textview in each cell
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            String animal = mData[position];
            holder.myTextView.setText(animal);
        }
    
        // total number of cells
        @Override
        public int getItemCount() {
            return mData.length;
        }
    
    
        // stores and recycles views as they are scrolled off screen
        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            TextView myTextView;
    
            ViewHolder(View itemView) {
                super(itemView);
                myTextView = (TextView) itemView.findViewById(R.id.info_text);
                itemView.setOnClickListener(this);
            }
    
            @Override
            public void onClick(View view) {
                if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
            }
        }
    
        // convenience method for getting data at click position
        String getItem(int id) {
            return mData[id];
        }
    
        // allows clicks events to be caught
        void setClickListener(ItemClickListener itemClickListener) {
            this.mClickListener = itemClickListener;
        }
    
        // parent activity will implement this method to respond to click events
        public interface ItemClickListener {
            void onItemClick(View view, int position);
        }
    }
    

    Notes

    • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

    Initialize RecyclerView in Activity

    Add the following code to your main activity.

    MainActivity.java

    public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
    
        MyRecyclerViewAdapter adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // data to populate the RecyclerView with
            String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};
    
            // set up the RecyclerView
            RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
            int numberOfColumns = 6;
            recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
            adapter = new MyRecyclerViewAdapter(this, data);
            adapter.setClickListener(this);
            recyclerView.setAdapter(adapter);
        }
    
        @Override
        public void onItemClick(View view, int position) {
            Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
        }
    }
    

    Notes

    • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

    Finished

    That's it. You should be able to run your project now and get something similar to the image at the top.

    Going on

    Rounded corners

    Auto-fitting columns

    Further study

    这篇关于使用RecyclerView和GridLayoutManager的简单Android网格示例(如旧的GridView)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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