यह उदाहरण दर्शाता है कि Kotlin का उपयोग करके Android में डायलॉग की स्क्रीन पर पोजीशन कैसे बदली जाती है। Window.setGravity() का उपयोग करके डायलॉग को स्क्रीन के किसी भी कोने में स्थित किया जा सकता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio खोलें, File → New Project पर जाएं और नया प्रोजेक्ट बनाने के लिए सभी आवश्यक विवरण भरें।
चरण 2: activity_main.xml में खाली लेआउट रखें
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>
चरण 3: MainActivity.kt में डायलॉग पोजीशन सेट करें
import android.os.Bundle
import android.view.Gravity
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle("Alert Dialog")
builder.setMessage("Have a nice day!")
builder.setCancelable(false)
builder.setPositiveButton("OK") { _, _ -> }.setNegativeButton("Cancel") { _, _ -> }
val alertDialog: AlertDialog = builder.create()
alertDialog.show()
alertDialog.window?.setGravity(Gravity.BOTTOM)
}
}
चरण 4: AndroidManifest.xml कॉन्फ़िगर करें
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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>
ऐप चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें। Android Studio में किसी एक्टिविटी फ़ाइल को खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और ऐप चलने पर डिफ़ॉल्ट स्क्रीन देखें।
नोट: Gravity.BOTTOM के अलावा आप Gravity.TOP, Gravity.LEFT, Gravity.RIGHT, Gravity.CENTER आदि का भी उपयोग कर सकते हैं।