Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Thay đổi vị trí Dialog trên màn hình Android bằng Kotlin

Hướng dẫn này minh họa cách thay đổi vị trí hiển thị Dialog trên màn hình Android sử dụng Kotlin.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (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>

Bước 3: Viết code 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(this)
        builder.setTitle("Alert Dialog")
        builder.setMessage("Have a nice day!")
        builder.setCancelable(false)
        builder.setPositiveButton("OK") { _, _ -> }
        builder.setNegativeButton("Cancel") { _, _ -> }

        val alertDialog = builder.create()
        alertDialog.show()
        alertDialog.window?.setGravity(Gravity.BOTTOM)
    }
}

Bước 4: Cấu hình 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Dialog sẽ xuất hiện ở vị trí góc dưới cùng màn hình (Gravity.BOTTOM) thay vì mặc định ở giữa màn hình.

Các tùy chọn Gravity khác

  • Gravity.TOP - Trên cùng
  • Gravity.CENTER - Giữa (mặc định)
  • Gravity.LEFT / Gravity.START - Bên trái
  • Gravity.RIGHT / Gravity.END - Bên phải
  • Gravity.TOP or Gravity.LEFT - Góc trên trái

Kết hợp với window?.setDimAmount(0.5f) để điều chỉnh độ mờ background nếu cần.