Diolog menyular va ulardan foydalanish.
Fragment klassi o'z hayot sikli bilan barcha standart fragment funktsiyalarini o'z ichiga oladi , ammo DialogFragment sinfidan meros bo'lib o'tadi, bu esa qo'shimcha funktsiyalarni qo'shadi. Va uni yaratish uchun biz ikkita usuldan foydalanishimiz mumkin:
Dialog ob'ektini qaytaradigan onCreateDialog() metodini bekor qilish.
Standart onCreateView() metodidan foydalanish.
OnCreateDialog() metodi dialog oynasini yaratish uchun AlertDialog.Builder sinfidan foydalanadi. Uning metodlaridan foydalanib , siz dialog oynasining ko'rinishini sozlashingiz mumkin:
setTitle: oynaning sarlavhasini o'rnatadi.
setView: oyna interfeysi layout-ini o'rnatadi.
setIcon: oyna ikonkasini o'rnatadi.
setPositiveButton: amalni tasdiqlash tugmachasini o'rnatadi.
setNeutralButton: tasdiqlash yoki bekor qilishdan farq qilishi mumkin bo'lgan "neytral" tugmachani o'rnatadi.
setNegativeButton: bekor qilish tugmachasini o'rnatadi.
setMessage: dialog oynasining matnini o'rnatadi, lekin setView-dan foydalanishda bu usul ixtiyoriy yoki agar biz shunchaki xabarni ko'rsatishni xohlasak, uni alternativ deb hisoblashimiz mumkin.
create: oyna yaratadi.
Bizni kodda, dialog oynasida faqat xabar ko'rsatiladi.
Dialog oynasini chaqirish uchun activity_main.xml faylida tugmachani qo'shing:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showDialog"
android:text="Dialog"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity kodida dialog oynasini ishga tushiradigan tugmacha uchun metodni aniqlang:
package com.example.android.dialogfragment;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showDialog(View v) {
CustomDialogFragment dialog = new CustomDialogFragment();
dialog.show(getSupportFragmentManager(), "custom");
}
}
Dialog oynasini chaqirish uchun CustomDialogFragment fragment ob'ekti yaratiladi, so'ngra unga show() metodi chaqiriladi. Ushbu metodga FragmentManager va teg parametr sifatida beriladi.
Ilovani ishga tushirib natijani ko'ramiz:
Dialog oynasini biroz sozlaymiz(o'zgartiramiz). Bu uchun CustomDialogFragment sinfidagi onCreateDialog metodini quyidagicha o'zgartiring:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
return builder
.setTitle("Muloqot oynasi")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Oynani yopish uchun OK tugmasini bosing")
.setPositiveButton("OK", null)
.setNegativeButton("Bekor qilish", null)
.create();
}
Bu kodda biz android.R.drawable.ic_dialog_alert resursini rasm sifatida ishlatadigan va ikkita tugmachani o'rnatadigan layoutni qo'shamiz.
Ilovani ishga tushiramiz.
Endi res/layout papkasiga yangi dialog.xml faylini qo'shing:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="OMUC"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Endi dialog oynasini o'zgartiring. Bu uchun CustomDialogFragment sinfidagi onCreateDialog metodini quyidagicha o'zgartiamiz:
package com.example.android.dialogfragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.DialogFragment;
public class CustomDialogFragment extends DialogFragment {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
return builder
.setTitle("Muloqot oynasi")
setIcon(android.R.drawable.ic_dialog_alert)
.setView(R.layout.dialog)
.setPositiveButton("OK", null)
.setNegativeButton("Bekor qilish", null)
.create();
}
}
package com.example.alertdialogs
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import androidx.core.view.GravityCompat
import com.example.alertdialogs.databinding.ActivityMainBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var selectedItemIndex = 0
private var arrItems = arrayOf("WHITE","BLACK")
var selectedItem = arrItems[selectedItemIndex]
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
// Aler Dialog 1
binding.button1.setOnClickListener {
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) { _, _ ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
builder.setNegativeButton(android.R.string.no) { _, _ ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
builder.setNeutralButton("Maybe") { _, _ ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()
}
//Alert Dialog 2
binding.button2.setOnClickListener {
val builder = AlertDialog.Builder(this)
.setTitle("o'yin tugadi")
.setCancelable(false)
.setMessage("Siz 12 ta savoldan 12 ta topdingiz!")
.setNegativeButton("Show high scores"){ _, _ ->
}
.setPositiveButton("Ok") { dialog, _ ->
dialog.dismiss()
}
// builder.show()
val dialog = builder.create()
dialog.show()
}
// Alert Dialog 3
binding.button3.setOnClickListener {
MyCustomDialog().show(supportFragmentManager, "MyCustomFragment")
}
// AlertDialog 4
binding.button4.setOnClickListener {
val array = arrayOf("WHITE","RED","GREEN","YELLOW","BLACK","MAGENTA","PINK")
Dilmurod Aka, [21.04.2022 11:21]
val builder = AlertDialog.Builder(this)
builder.setTitle("Choose a color.")
builder.setItems(array) { _, which ->
val selected = array[which]
try {
root_layout.setBackgroundColor(Color.parseColor(selected))
Toast.makeText(this, "$selected color selected.", Toast.LENGTH_SHORT)
.show()
} catch (e: IllegalArgumentException) {
// Catch the color string parse exception
Toast.makeText(
this,
"$selected Color not supported.",
Toast.LENGTH_SHORT
).show()
}
}
val dialog = builder.create()
dialog.show()
}
// AlertDialog 5
binding.button5.setOnClickListener {
MaterialAlertDialogBuilder(this)
.setTitle("Orqa fonni o'zgartirish")
.setSingleChoiceItems(arrItems, selectedItemIndex) { dialog, which ->
selectedItemIndex = which
selectedItem = arrItems[which]
button5.text = selectedItem
root_layout.setBackgroundColor(Color.parseColor(selectedItem))
dialog.dismiss()
}.show()
}
}
}package com.example.alertdialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import kotlinx.android.synthetic.main.custom_dailog_layout.*
class MyCustomDialog: DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog!!.window?.setBackgroundDrawableResource(R.drawable.round_corner)
return inflater.inflate(R.layout.custom_dailog_layout, container , false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_login.setOnClickListener {
dialog!!.dismiss()
}
}
override fun onStart() {
super.onStart()
dialog!!.setCancelable(false)
val width = (resources.displayMetrics.widthPixels * 0.85).toInt()
val height = (resources.displayMetrics.heightPixels * 0.40).toInt()
dialog!!.window?.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT)
}
}
package com.example.alertdialogs
import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import kotlinx.android.synthetic.main.activity_main.*
class MyDialogFragment: DialogFragment() {
lateinit var programmingLanguages: ArrayList
@SuppressLint("UseRequireInsteadOfGet")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val array = arrayOf("RED","GREEN","YELLOW","BLACK","MAGENTA","PINK")
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Choose a color.")
builder.setItems(array) { _, which ->
val selected = array[which]
try {
root_layout.setBackgroundColor(Color.parseColor(selected))
Toast.makeText(requireActivity(), "$selected color selected.", Toast.LENGTH_SHORT)
.show()
} catch (e: IllegalArgumentException) {
// Catch the color string parse exception
Toast.makeText(
requireActivity(),
"$selected Color not supported.",
Toast.LENGTH_SHORT
).show()
}
}
val dialog = builder.create()
dialog.show()
return super.onCreateDialog(savedInstanceState)
}
}
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:id="@+id/root_layout"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="40dp"
android:text="AlertDialog1"
android:textAllCaps="false" />
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="40dp"
android:text="AlertDialog2"
android:textAllCaps="false" />
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="40dp"
android:text="AlertDialog3"
android:textAllCaps="false" />
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="40dp"
android:text="AlertDialog4"
android:textAllCaps="false" />
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="40dp"
android:text="AlertDialog5"
android:textAllCaps="false" />
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/tv_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="LOGIN"
android:textSize="20sp"
android:text
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
android:id="@+id/et_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="Username"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_login" />
android:id="@+id/et_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_username" />
app:cornerRadius="8dp"
android:id="@+id/btn_login"
android:layout_width="0dp"
android:layout_height="36dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:background="#2196F3"
android:text="Login"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_password" />
android:id="@+id/img_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="@+id/et_username"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_login"
app:srcCompat="@drawable/ic_baseline_account_circle_24" />
android:id="@+id/img_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="@+id/et_password"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_username"
app:srcCompat="@drawable/ic_baseline_lock_24" />
SetView() metodi avval qo'shilgan layout dialog.xml resursini oyna interfeysi sifatida o'rnatadi. Endi yana ilovani ishga tushiring va natijani ko'ring:
Xulosa.
Men ushbu labaratoriyani bajarish mobaynida Android Studio muhitidan foydalanish bilimlarimni oshirib oldim. Bu labaratoriya ishida Android Studioda menyu yaratish., Android Studioda NavigotionMenu va ContextMenudan foydalanish , Android Studioda Diolog menyular va ulardan foydalanishni ko’rib chiqdim va bulardan amaliyotda foydalandim.
Dostları ilə paylaş: