简体   繁体   English

是否可以根据屏幕宽度使用gridLayoutManager调整recyclerview的行数和列数?

[英]Is it possible to adjust the number of rows and columns of recyclerview using gridLayoutManager according to the screen width?

In a course of developing an Android app, something happened to show the user a list of items.在开发 Android 应用程序的过程中,发生了一些事情来向用户显示项目列表。 If you are looking at a mobile phone vertically, the number of rows are not limited, but if you are looking horizontally, you want to create a function that allows you to adjust the number of columns according to the width.如果你是垂直看手机,行数没有限制,但如果你是水平看,你想创建一个function,允许你根据宽度调整列数。 This is the code I am currently using.这是我目前正在使用的代码。

class MainActivity : AppCompatActivity() {
    var array: ArrayList<String>? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        ...
        recyclerView.layoutManager = GirdLayoutManager(this, 2)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = MyAdapter(array!!)
    }
}

Since the value of spanCount is set to 2, of course, I know that the number of columns is set to 2. I just want the width of the itemView I want to show is properly adjusted according to the mobile width.既然spanCount的值设置为2,当然我知道列数设置为2。我只是想让我要显示的itemView的宽度根据移动宽度适当调整。 Is there any solution?有什么解决办法吗?

If you need a custom GridLayout manager, how do you make it?如果你需要一个自定义的GridLayout管理器,你是怎么做的?

You could add integer resource file into res/values that holds different variants of the spanCount value that you want to vary for different screen widths.您可以将 integer 资源文件添加到 res/values 中,其中包含您希望针对不同屏幕宽度而变化的spanCount值的不同变体。

Right Click on on res/values > New > Values Resource File > Pick a name for the file > select Screen Width qualifier and set the screen width value in dp右键单击 res/values > New > Values Resource File > 为文件选择一个名称 > select Screen Width qualifier并在dp中设置屏幕宽度值

在此处输入图像描述

Then add an integer value然后添加一个 integer 值

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="span">2</integer>
</resources>

Repeat this for different screen widths you want the span vary in. And of course create the default resource file that match any other screen width you didn't mention (that has no qualifiers identified.)对您希望跨度变化的不同屏幕宽度重复此操作。当然,创建与您未提及的任何其他屏幕宽度匹配的默认资源文件(未识别限定符。)

And to build the recyclerView span get that resource, and it automatically takes the appropriate resource value according to the screen width:并构建 recyclerView span 获取该资源,它会根据屏幕宽度自动获取适当的资源值:

recyclerView.layoutManager = GirdLayoutManager(this, resources.getInteger(R.integer.span))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM