Dialogu i alarmit Android duke përdorur Kotlin
Në këtë tutorial, ne do të diskutojmë Dialogjet e alarmit dhe do t'i zbatojmë ato në aplikacionin tonë Android duke përdorur Kotlin.
Dialogët e alarmit
Alert Dialog është një dritare që shfaqet në ekran. Ata zakonisht tregojnë disa informacione dhe kërkojnë një veprim të përdoruesit. Ka tre komponentë thelbësorë që ndërtojnë një Dialog Alert.
- Teksti i titullit
- Tekst i mesazhit
- Butonat - Ekzistojnë tre lloje butonash: Pozitiv, Negativ dhe Neutral
Për të krijuar një AlertDialog ne përdorim klasën e brendshme AlertDialog.Builder
.
val alertDialogBuilder = AlertDialog.Builder(this)
Ne e kalojmë kontekstin brenda konstruktorit. Opsionale, mund të kalojmë një parametër tjetër, stilin e dialogut të alarmit.
Metodat e dialogut të alarmit
Disa nga metodat që mund të përdoren në një AlertDialog.
- setTitle
- setMesazh
- setIcon
- setCustomTitle - Këtu mund të kaloni një pamje të personalizuar që do të vendoset në vend të pjesës së titullit në dialogun e sinjalizimit.
- setPositiveButton - Ne kalojmë emrin e vargut, si dhe butonin, metodën e kthimit të thirrjes klikuar këtu.
- setView - përdoret për të shtuar një pamje të personalizuar brenda dialogut të sinjalizimit.
- setList - përdoret për të vendosur një grup vargjesh që do të shfaqen në formën e një Liste.
- setMultiChoiceList - përsëri ne mund të vendosim një grup, por këtë herë mund të zgjedhim disa artikuj nga Lista falë CheckBox.
- setPositiveButtonIcon - vendosni një ikonë krahas butonit
- show() - përdoret për të shfaqur AlertDialog
- setDississListener - Brenda kësaj, mund të caktoni logjikën që do të aktivizohet kur dialogu i sinjalizimit hiqet.
- setShowListener - cakto logjikën që do të aktivizohet kur dialogu i sinjalizimeve hiqet.
- setCancelable - kërkon një vlerë boolean. Si parazgjedhje, të gjitha dialogët e sinjalizimit mund të anulohen kur klikoni ose prekni butonin jashtë. Nëse kjo metodë është caktuar në false, duhet të anuloni në mënyrë të qartë dialogun duke përdorur metodën dialog.cancel().
Kodi Kotlin i dialogut të alarmit
Për të përdorur AlertDialog në projektin tuaj Android Studio, importoni klasën e mëposhtme.
import android.support.v7.app.AlertDialog;
Ndjekja e kodit Kotlin përdoret për të krijuar një dialog të thjeshtë alarmi.
val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")
//builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = x))
builder.setPositiveButton(android.R.string.yes) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
builder.setNegativeButton(android.R.string.no) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
builder.setNeutralButton("Maybe") { dialog, which ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()
builder.show()
shfaq dialogun e alarmit në ekran. Brenda funksionit setPositiveButton
, ne kalojmë tekstin e Butonit së bashku me një funksion Kotlin që aktivizohet kur klikohet ai buton. Funksioni është pjesë e ndërfaqes DialogInterface.OnClickListener()
. Lloji i funksionit është (DialogInterface, Int) -> Njësi
. DialogInterface është një shembull i Dialogut dhe Int është id i butonit që klikohet. Në kodin e mësipërm, ne e kemi paraqitur këtë funksion si një funksion Kotlin të Rendit të Lartë. dialog
dhe i cili
përfaqëson dy argumentet. Ne mund ta përmirësojmë funksionin duke kaluar _ nëse argumentet nuk përdoren. Funksionet do të duken si këto:
builder.setPositiveButton(android.R.string.yes) { _,_ ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
Përndryshe, ne gjithashtu mund të shfaqim Dialog përmes instancës së klasës AlertDialog. Zëvendësoni builder.show()
me:
val alertDialog = builder.create()
alertDialog.show()
Në vend që të përcaktojmë funksionet e dëgjuesit të klikimeve të butonit për secilin nga butonat, ne mund të përcaktojmë veçmas edhe funksionet e rendit më të lartë.
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
Tani vendosni këtë veti val
brenda funksionit setPositiveButton
Kotlin si:
builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
//or
builder.setPositiveButton(android.R.string.yes, positiveButtonClick)
Ju mund të kaloni një null në vend të funksionit nëse nuk keni ndërmend të mbani ndonjë veprim në klikimin e butonit.
Kotlin ka akoma më shumë fuqi për të përmirësuar lexueshmërinë e kodit të mësipërm.
Kodi Kotlin i Dialogut të Simple Alert
Duke përdorur funksionin me
, ne mund të përmirësojmë lexueshmërinë e kodit Kotlin për të krijuar një Dialog Alert.
fun basicAlert(view: View){
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
Në seksionin tjetër ne do të krijojmë aplikacionin tonë Android ku do të zbatojmë veçoritë e mëposhtme në AlertDialog tonë.
- Dialog i thjeshtë i sinjalizimit
- Dialogu i sinjalizimit me personalizimin e ikonave dhe butonave
- Dialogu i sinjalizimit me listën
- Dialogu i sinjalizimit me listën e shumëzgjedhjeve
- Dialogu i sinjalizimit me stilin
- Dialogu i sinjalizimit me stilin e personalizuar
- Dialogu i sinjalizimit me EditText
Struktura e projektit Android Studio
1. Kodi i paraqitjes XML
Kodi për paraqitjen activity_main.xml jepet më poshtë.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnBasicAlert"
android:layout_width="wrap_content"
android:onClick="basicAlert"
android:layout_height="wrap_content"
android:text="BASIC ALERT DIALOG" />
<Button
android:id="@+id/btnAlertWithIconsAndCustomize"
android:layout_width="wrap_content"
android:onClick="withIconAndCustomise"
android:layout_height="wrap_content"
android:text="WITH ICON AND CUSTOMIZATION" />
<Button
android:id="@+id/btnAlertWithItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withItems"
android:text="WITH ITEMS" />
<Button
android:id="@+id/btnAlertWithMultiChoiceList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withMultiChoiceList"
android:text="WITH MULTI CHOICE LIST" />
<Button
android:id="@+id/btnAlertWithStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withStyle"
android:text="WITH STYLE" />
<Button
android:id="@+id/btnAlertWithCustomStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withCustomStyle"
android:text="WITH CUSTOM STYLE" />
<Button
android:id="@+id/btnAlertWithButtonCentered"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withButtonCentered"
android:text="WITH BUTTON CENTERED" />
<Button
android:id="@+id/btnAlertWithEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withEditText"
android:text="WITH EDIT TEXT" />
</LinearLayout>
Për secilin nga butonat ne kemi vendosur një atribut android:onClick
me emrin e funksionit. Këto funksione Kotlin do të aktivizohen në klasën MainActivity.kt. Ne do të diskutojmë secilën prej tyre një nga një.
2. Kodi i Aktivitetit Kryesor Kotlin
Ne kemi krijuar tashmë Dialogun e parë të Alert më lart. Le të shohim se si duket MainActivity.kt me të.
package net.androidly.androidlyalertdialog
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.Toast
class MainActivity : AppCompatActivity() {
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
val negativeButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
val neutralButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun basicAlert(view: View){
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
}
3. Dialogu i alarmit me ikona dhe personalizimi
val builder = AlertDialog.Builder(this)
with(builder) {
setTitle("Icon and Button Color")
setMessage("We have a message")
setPositiveButton("OK", null)
setNegativeButton("CANCEL", null)
setNeutralButton("NEUTRAL", null)
setPositiveButtonIcon(resources.getDrawable(android.R.drawable.ic_menu_call, theme))
setIcon(resources.getDrawable(android.R.drawable.ic_dialog_alert, theme))
}
val alertDialog = builder.create()
alertDialog.show()
val button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
with(button) {
setBackgroundColor(Color.BLACK)
setPadding(0, 0, 20, 0)
setTextColor(Color.WHITE)
}
Duke përdorur getButton
, ne mund të marrim cilindo nga Butonat duke vendosur konstantën e tyre përkatëse. Pasi të merret Butoni, ne mund ta personalizojmë siç u bë më sipër.
4. Dialogu i alarmit me artikujt
fun withItems(view: View) {
val items = arrayOf("Red", "Orange", "Yellow", "Blue")
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("List of Items")
setItems(items) { dialog, which ->
Toast.makeText(applicationContext, items[which] + " is clicked", Toast.LENGTH_SHORT).show()
}
setPositiveButton("OK", positiveButtonClick)
show()
}
}
Brenda setItems kalojmë grupin Kotlin. Argumenti which
përfaqëson indeksin e elementit të klikuar në Listë.
5. Dialogu i alarmit me listën e shumëzgjedhjeve
fun withMultiChoiceList(view: View) {
val items = arrayOf("Microsoft", "Apple", "Amazon", "Google")
val selectedList = ArrayList<Int>()
val builder = AlertDialog.Builder(this)
builder.setTitle("This is list choice dialog box")
builder.setMultiChoiceItems(items, null
) { dialog, which, isChecked ->
if (isChecked) {
selectedList.add(which)
} else if (selectedList.contains(which)) {
selectedList.remove(Integer.valueOf(which))
}
}
builder.setPositiveButton("DONE") { dialogInterface, i ->
val selectedStrings = ArrayList<string>()
for (j in selectedList.indices) {
selectedStrings.add(items[selectedList[j]])
}
Toast.makeText(applicationContext, "Items selected are: " + Arrays.toString(selectedStrings.toTypedArray()), Toast.LENGTH_SHORT).show()
}
builder.show()
}
Në kodin e mësipërm, ne i ruajmë zgjedhjet në një listë me numra të plotë dhe i marrim përsëri për t'i shfaqur në mesazhin Toast.
6. Dialogu i alarmit me stilin
fun withStyle(view: View) {
val builder = AlertDialog.Builder(ContextThemeWrapper(this, android.R.style.Holo_SegmentedButton))
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
Nëse nuk përdorni ContextThemeWrapper, Dialogu i Alert do të shfaqet në ekranin e plotë.
7. Dialogu i alarmit me stil të personalizuar
Shtoni kodin e mëposhtëm në skedarin styles.xml:
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog">
<item name="android:textColor">@android:color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:headerDividersEnabled">true</item>
<item name="android:background">@android:color/holo_blue_dark</item>
</style>
Më poshtë është funksioni Kotlin:
fun withCustomStyle(view: View) {
val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AlertDialogCustom))
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
8. Dialogu i alarmit me butonin në qendër
fun withButtonCentered(view: View) {
val alertDialog = AlertDialog.Builder(this).create()
alertDialog.setTitle("Title")
alertDialog.setMessage("Message")
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes"
) { dialog, which -> dialog.dismiss() }
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No"
) { dialog, which -> dialog.dismiss() }
alertDialog.show()
val btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
val btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 10f
btnPositive.layoutParams = layoutParams
btnNegative.layoutParams = layoutParams
}
9. Dialogu i alarmit me modifikimin e tekstit
Kodi për paraqitjen e personalizuar alert_dialog_with_edittext.xml jepet më poshtë:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the text here"/>
</LinearLayout>
fun withEditText(view: View) {
val builder = AlertDialog.Builder(this)
val inflater = layoutInflater
builder.setTitle("With EditText")
val dialogLayout = inflater.inflate(R.layout.alert_dialog_with_edittext, null)
val editText = dialogLayout.findViewById<EditText>(R.id.editText)
builder.setView(dialogLayout)
builder.setPositiveButton("OK") { dialogInterface, i -> Toast.makeText(applicationContext, "EditText is " + editText.text.toString(), Toast.LENGTH_SHORT).show() }
builder.show()
}
Shkarkoni Projektin Android Studio: AndroidlyAlertDialog