กดปุ่มแล้วจะแสดง dialog ถ้าตอบ Yes จะเปลี่ยนสี background ของ activity นี้เป็นสีแดง
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Show Me Alert Dialog" /> </LinearLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.graphics.Color import android.support.v7.app.AlertDialog import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Set a click listener for button widget button.setOnClickListener { // Initialize a new instance of val builder = AlertDialog.Builder(this@MainActivity) // Set the alert dialog title builder.setTitle("App background color") // Display a message on alert dialog builder.setMessage("Are you want to set the app background color to RED?") // Set a positive button and its click listener on alert dialog builder.setPositiveButton("YES") { dialog, which -> // Do something when user press the positive button Toast.makeText(applicationContext, "Ok, we change the app background.", Toast.LENGTH_SHORT).show() // Change the app background color root_layout.setBackgroundColor(Color.RED) } // Display a negative button on alert dialog builder.setNegativeButton("No") { dialog, which -> Toast.makeText(applicationContext, "You are not agree.", Toast.LENGTH_SHORT).show() } // Display a neutral button on alert dialog builder.setNeutralButton("Cancel") { _, _ -> Toast.makeText(applicationContext, "You cancelled the dialog.", Toast.LENGTH_SHORT).show() } // Finally, make the alert dialog using builder val dialog: AlertDialog = builder.create() // Display the alert dialog on app interface dialog.show() } } } |
บรรทัดที่ 33 : เปลี่ยนสีของ background ด้วย setBackgroundColor()
Link