شرح التعامل مع Alert Dialog نافذة التنبيه
تقريباً لا يوجد تطبيق لا توجد به نافذة لاخبار المستخدم بشيئ معين او لعرض شيئ داخل التطبيق لا يحتاج لواجهة جديدة بحيث تنبسق نافذة صغير لاظهار رسالة ما للمستخدم ممكن استخدامه بطريقة بسيطة برمجيا لاظهار النافذة مع زر للموافقة او عدم الموافقة وممكن برمجة نافذة مخصصة custom مع العناصر الذي نحتاجها بها كـ Button or list or radiobutton او ايا شيئ نحتاجه
بهذا الشرح سوف نستخدمها لعرض رسالة للمستخدم فقط نظهر رسالة وزر لاغلاق النافذة وعنوان الرسالة
كود xml
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:layout_margin="16dp" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:hint="Add your name" android:inputType="text" /> <Button android:onClick="showAlert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="OnClick" /> </LinearLayout> |
كود kotlin
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 |
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.View 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) } fun showAlert(view : View) { val alert = AlertDialog.Builder(this) // get name from edit text val name = editText.text.toString() // Check if name empty if (!name.isBlank()) { // Builder with(alert) { // Alert dialog Title setTitle("Alert Dialog") // Alert dialog message setMessage("Your name is : $name") // Alert dialog Button setNegativeButton("ok") { dialog, whichButton -> // Hide dialog after press ok dialog.dismiss() } } val dialog = alert.create() dialog.show() } else { Toast.makeText(this, "is empty", Toast.LENGTH_SHORT).show() } } } |
في حالة الفحص لنص تم استخدام isBlank
ممكن استخدام دالة isEmpty ولكن بهذه الحالة اذا ادخل مسافة فقط سوف يقبل الادخال ولكن دالة isBlank لن يقبل الادخال فارغاً او ادخال فقط مساحة space