यह उदाहरण दर्शाता है कि Kotlin में प्रोग्रामेटिक रूप से GridLayout में व्यू जोड़कर उसे स्क्रीन आकार में फिट कैसे किया जाए।
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio: File → New Project।
चरण 2 - activity_main.xml में GridLayout
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/tableGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:columnCount="4"
android:orientation="horizontal"
tools:context=".MainActivity">
<!-- प्रोग्रामेटिक रूप से भरा जाएगा -->
</GridLayout>
चरण 3 - MainActivity.kt में डायनामिक ग्रिड भरें
import android.os.Bundle
import android.view.Gravity
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.TableLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val gridLayout = findViewById<GridLayout>(R.id.tableGrid)
gridLayout.removeAllViews()
val totalItems = 12
val columnCount = 5
val rowCount = (totalItems + columnCount - 1) / columnCount // सीलिंग डिवीजन
gridLayout.columnCount = columnCount
gridLayout.rowCount = rowCount
for (i in 0 until totalItems) {
val column = i % columnCount
val row = i / columnCount
val imageView = ImageView(this).apply {
setImageResource(R.drawable.ic_launcher_background)
scaleType = ImageView.ScaleType.CENTER_CROP
}
val params = GridLayout.LayoutParams().apply {
height = TableLayout.LayoutParams.WRAP_CONTENT
width = 0 // 0 + columnSpec.weight = समान चौड़ाई
columnSpec = GridLayout.spec(column, 1f) // 1f = समान वजन
rowSpec = GridLayout.spec(row)
setGravity(Gravity.CENTER)
rightMargin = 8
bottomMargin = 8
}
imageView.layoutParams = params
gridLayout.addView(imageView)
}
}
}
चरण 4 - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.gridlayoutfit">
<application ...>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
ऐप चलाएं। GridLayout में 5 कॉलम और 3 पंक्तियों में 12 इमेज व्यू समान आकार में प्रदर्शित होंगे, स्क्रीन चौड़ाई को भरते हुए।
महत्वपूर्ण सुधार: मूल कोड में `width = WRAP_CONTENT` था जिससे कॉलम असमान होते थे। ऊपर दिए गए कोड में `width = 0` और `columnSpec.weight = 1f` का उपयोग करके समान चौड़ाई सुनिश्चित की गई है।
आधुनिक विकल्प:RecyclerViewके साथGridLayoutManagerका उपयोग करना अधिक कुशल और लचीला है, विशेष रूप से बड़ी सूचियों के लिए।