Android Studio muhitida menyular va dialog oynalar bilan ishlash


Diolog menyular va ulardan foydalanish



Yüklə 28,75 Kb.
səhifə4/4
tarix29.04.2022
ölçüsü28,75 Kb.
#56707
1   2   3   4
mobil ilovalar 3

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">


Yüklə 28,75 Kb.

Dostları ilə paylaş:
1   2   3   4




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin