In a course of developing an Android app, something happened to show the user a list of items. 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. 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. Is there any solution?

If you need a custom GridLayout manager, how do you make it?

2
hanjiman 5 Juli 2020, 04:53

1 menjawab

Jawaban Terbaik

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.

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

enter image description here

Then add an integer value

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

Ulangi ini untuk lebar layar berbeda yang Anda inginkan rentangnya bervariasi. Dan tentu saja buat file sumber daya default yang cocok dengan lebar layar lain yang tidak Anda sebutkan (yang tidak memiliki kualifikasi yang diidentifikasi.)

And to build the recyclerView span get that resource, and it automatically takes the appropriate resource value according to the screen width:

recyclerView.layoutManager = GirdLayoutManager(this, resources.getInteger(R.integer.span))
2
Zain 5 Juli 2020, 06:41