Dalam aplikasi Android, saya ingin menampilkan tampilan daftar kustom di AlertDialog.
Bagaimana saya bisa melakukan ini?
Dalam aplikasi Android, saya ingin menampilkan tampilan daftar kustom di AlertDialog.
Bagaimana saya bisa melakukan ini?
Jawaban:
Digunakan kode di bawah ini untuk menampilkan daftar khusus di AlertDialog
AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Your Selected Item is");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
}
});
builderInner.show();
}
});
builderSingle.show();
Menurut dokumentasi , ada tiga jenis daftar yang dapat digunakan dengan AlertDialog
:
Saya akan memberikan contoh masing-masing di bawah ini.
Cara membuat daftar pilihan tunggal tradisional adalah menggunakan setItems
.
Versi Java
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // horse
case 1: // cow
case 2: // camel
case 3: // sheep
case 4: // goat
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Tidak perlu tombol OK karena segera setelah pengguna mengklik pada kontrol item daftar dikembalikan ke OnClickListener
.
Versi Kotlin
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
when (which) {
0 -> { /* horse */ }
1 -> { /* cow */ }
2 -> { /* camel */ }
3 -> { /* sheep */ }
4 -> { /* goat */ }
}
}
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
Keuntungan dari daftar tombol radio di atas daftar tradisional adalah bahwa pengguna dapat melihat apa pengaturan saat ini. Cara membuat daftar tombol radio adalah menggunakan setSingleChoiceItems
.
Versi Java
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user checked an item
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Saya sulit mengkodekan item yang dipilih di sini, tetapi Anda dapat melacaknya dengan variabel anggota kelas dalam proyek nyata.
Versi Kotlin
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
// user checked an item
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
Cara membuat daftar kotak centang adalah menggunakan setMultiChoiceItems
.
Versi Java
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");
// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Di sini saya sulit mengkodekan item mana dalam daftar yang sudah diperiksa. Ini lebih mungkin bahwa Anda ingin melacak mereka dalam ArrayList<Integer>
. Lihat contoh dokumentasi untuk lebih jelasnya. Anda juga dapat mengatur item yang dicentang ke null
jika Anda selalu ingin semuanya dimulai tidak dicentang.
Versi Kotlin
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")
// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
// user checked or unchecked a box
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
context
di dalam kode di atas, jangan gunakan getApplicationContext()
atau Anda akan mendapatkan IllegalStateException
(lihat di sini untuk alasannya). Alih-alih, dapatkan referensi ke konteks aktivitas, seperti dengan this
.setAdapter
atau setCursor
atau lewat di Cursor
atau ListAdapter
ke dalam setSingleChoiceItems
atau setMultiChoiceItems
.Untuk menguji semua contoh di atas, saya hanya punya proyek sederhana dengan satu tombol daripada menunjukkan dialog ketika diklik:
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
}
public void showAlertDialogButtonClicked(View view) {
// example code to create alert dialog lists goes here
}
}
RecyclerView
tata letak untuk itu.
BUTTON_POSITIVE
) atau posisi item diklik".
Builder.setAdapter(ListAdapter, DialogInterface.OnClickListener)
: which
di listener onClick
akan sama dengan posisi item yang diklik. Builder.setOnItemSelectedListener
tidak akan berpengaruh.
Anda dapat menggunakan dialog khusus.
Tata letak dialog khusus. list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="fill_parent"/>
</LinearLayout>
Dalam aktivitas Anda
Dialog dialog = new Dialog(Activity.this);
dialog.setContentView(R.layout.list)
ListView lv = (ListView ) dialog.findViewById(R.id.lv);
dialog.setCancelable(true);
dialog.setTitle("ListView");
dialog.show();
Edit:
Menggunakan alertdialog
String names[] ={"A","B","C","D"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
Jepret
final CharSequence[] items = {"A", "B", "C"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
mDoneButton.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
ListAdapter
with setSingleChoiceItems
(sangat mirip dengan panggilan di atas)
Gunakan import android.app.AlertDialog;
impor " " dan kemudian Anda menulis
String[] items = {"...","...."};
AlertDialog.Builder build = new AlertDialog.Builder(context);
build.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do stuff....
}
}).create().show();
show()
melakukan keduanya. Calling this method is functionally identical to: AlertDialog dialog = builder.create(); dialog.show();
itu langsung dari show()
dokumentasi metode
Ini terlalu sederhana
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
getCapturesProfilePicFromCamera();
} else if (items[item].equals("Choose from Library")) {
getProfilePicFromGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
Sebagai seorang pemula, saya sarankan Anda mengunjungi http://www.mkyong.com/android/android-custom-dialog-example/
Saya akan rundown apa yang dasarnya
Dialog
dialog.show()
metode.Di Kotlin:
fun showListDialog(context: Context){
// setup alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an Item")
// add list items
val listItems = arrayOf("Item 0","Item 1","Item 2")
builder.setItems(listItems) { dialog, which ->
when (which) {
0 ->{
Toast.makeText(context,"You Clicked Item 0",Toast.LENGTH_LONG).show()
dialog.dismiss()
}
1->{
Toast.makeText(context,"You Clicked Item 1",Toast.LENGTH_LONG).show()
dialog.dismiss()
}
2->{
Toast.makeText(context,"You Clicked Item 2",Toast.LENGTH_LONG).show()
dialog.dismiss()
}
}
}
// create & show alert dialog
val dialog = builder.create()
dialog.show()
}
Ini adalah cara menampilkan dialog tata letak khusus dengan item daftar kustom, dapat disesuaikan sesuai kebutuhan Anda.
LANGKAH - 1 Buat tata letak DialogBox yaitu: -
R.layout.assignment_dialog_list_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_round_corner_assignment_alert"
android:orientation="vertical">
<TextView
android:id="@+id/tv_popup_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:singleLine="true"
android:paddingStart="4dp"
android:text="View as:"
android:textColor="#4f4f4f" />
<ListView
android:id="@+id/lv_assignment_users"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
LANGKAH - 2 Buat tata letak item daftar khusus sesuai logika bisnis Anda
R.layout.item_assignment_dialog_list_layout
<?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="wrap_content"
android:gravity="center"
android:padding="4dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_user_profile_image"
android:visibility="visible"
android:layout_width="42dp"
android:layout_height="42dp" />
<TextView
android:id="@+id/tv_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:layout_marginStart="8dp"
android:paddingBottom="8dp"
android:textColor="#666666"
android:textSize="18sp"
tools:text="ABCD XYZ" />
</LinearLayout>
LANGKAH - 3 Buat kelas model data pilihan Anda sendiri
public class AssignmentUserModel {
private String userId;
private String userName;
private String userRole;
private Bitmap userProfileBitmap;
public AssignmentUserModel(String userId, String userName, String userRole, Bitmap userProfileBitmap) {
this.userId = userId;
this.userName = userName;
this.userRole = userRole;
this.userProfileBitmap = userProfileBitmap;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public Bitmap getUserProfileBitmap() {
return userProfileBitmap;
}
public void setUserProfileBitmap(Bitmap userProfileBitmap) {
this.userProfileBitmap = userProfileBitmap;
}
}
LANGKAH - 4 Buat adaptor khusus
public class UserListAdapter extends ArrayAdapter<AssignmentUserModel> {
private final Context context;
private final List<AssignmentUserModel> userList;
public UserListAdapter(@NonNull Context context, int resource, @NonNull List<AssignmentUserModel> objects) {
super(context, resource, objects);
userList = objects;
this.context = context;
}
@SuppressLint("ViewHolder")
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_assignment_dialog_list_layout, parent, false);
ImageView profilePic = rowView.findViewById(R.id.iv_user_profile_image);
TextView userName = rowView.findViewById(R.id.tv_user_name);
AssignmentUserModel user = userList.get(position);
userName.setText(user.getUserName());
Bitmap bitmap = user.getUserProfileBitmap();
profilePic.setImageDrawable(bitmap);
return rowView;
}
}
LANGKAH - 5 Buat fungsi ini dan berikan ArrayList model data di atas dalam metode ini
// Pass list of your model as arraylist
private void showCustomAlertDialogBoxForUserList(ArrayList<AssignmentUserModel> allUsersList) {
final Dialog dialog = new Dialog(mActivity);
dialog.setContentView(R.layout.assignment_dialog_list_view);
if (dialog.getWindow() != null) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // this is optional
}
ListView listView = dialog.findViewById(R.id.lv_assignment_users);
TextView tv = dialog.findViewById(R.id.tv_popup_title);
ArrayAdapter arrayAdapter = new UserListAdapter(context, R.layout.item_assignment_dialog_list_layout, allUsersList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener((adapterView, view, which, l) -> {
Log.d(TAG, "showAssignmentsList: " + allUsersList.get(which).getUserId());
// TODO : Listen to click callbacks at the position
});
dialog.show();
}
Langkah - 6 Memberikan latar belakang sudut bundar ke kotak dialog
@ drawable / rectangle_round_corner_assignment_alert
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff" />
<corners android:radius="16dp" />
<padding
android:bottom="16dp"
android:left="16dp"
android:right="16dp"
android:top="16dp" />
</shape>
Bukankah lebih halus untuk membuat metode yang dipanggil setelah pembuatan unit EditText di AlertDialog, untuk penggunaan umum?
public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(SelectTitle);
builder.setItems(SelectList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
EditTextItem.setText(SelectList[item]);
}
});
builder.create().show();
return false;
}
});
}
private void AlertDialogue(final List<Animals> animals) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AdminActivity.this);
alertDialog.setTitle("Filter by tag");
final String[] animalsArray = new String[animals.size()];
for (int i = 0; i < tags.size(); i++) {
animalsArray[i] = tags.get(i).getanimal();
}
final int checkedItem = 0;
alertDialog.setSingleChoiceItems(animalsArray, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "onClick: " + animalsArray[which]);
}
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
}