创建带单选按钮列表的自定义对话框。

35

我有一个方法,其中包含一列值:

     /**
     * ISO
     * */
    public void getISO(View view) {
        // Open dialog with radio buttons
        List<String> supported_isos = preview.getSupportedISOs();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        String current_iso = sharedPreferences.getString(MainActivity.getISOPreferenceKey(), "auto");

    }

该方法被注入到一个 ImageButton 的 onClick() 事件中:

android:onClick="getISO"

但我需要在对话框中用单选按钮来表示这个列表。最好在对话框中预先选择好偏好值。这可行吗?


这是可能的,一切取决于您如何填充对话框。 - JoxTraex
1
创建一个对话框并将自定义视图设置到其中。 - Rustam
你能给我展示一下使用我的List的例子吗? - Atlas91
从这里开始 @ http://developer.android.com/guide/topics/ui/dialogs.html - JoxTraex
如果您正在寻找一个不需要自定义视图的更简单的解决方案,请查看我的解决方案,它将为您提供与标准Android警报对话框相同的体验,如果您不想做超出此范围的事情。 - JoxTraex
8个回答

77

最佳且简单的方法......

void dialog(){

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        //alt_bld.setIcon(R.drawable.icon);
        alt_bld.setTitle("Select a Group Name");
        alt_bld.setSingleChoiceItems(grpname, -1, new DialogInterface
                .OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(),
                        "Group Name = "+grpname[item], Toast.LENGTH_SHORT).show();
                dialog.dismiss();// dismiss the alertbox after chose option

            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();


///// grpname is a array where data is stored... 


    }

这不是自定义的警告对话框,而是带有单选项的默认警告对话框。 - user924
如果你想要一个“确认”按钮,只需使用setPositiveButton像通常一样将其添加到对话框中,并从上面的代码中删除dialog.dismiss() - FirstOne

41

从按钮调用showRadioButtonDialog()

这只是一个例子:

private void showRadioButtonDialog() {

 // custom dialog

  final Dialog dialog = new Dialog(this);
  dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
  dialog.setContentView(R.layout.dialog_layout);
  List<String> stringList=new ArrayList<>();  // here is list
      for(int i=0;i<2;i++) {
          if (i==0){
              stringList.add("Number Mode");
          }else {
              stringList.add("Character Mode");
          }

      }

      RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radioGroup);

      for(int i=0;i<stringList.size();i++){
            RadioButton rb=new RadioButton(this); // dynamically creating RadioButton and adding to RadioGroup.
            rb.setText(stringList.get(i));
            rg.addView(rb);
      }
}

您的布局视图可能是:radiobutton_dialog.xml

<?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:orientation="vertical">
      <RadioGroup
          android:id="@+id/radio_group"
          android:layout_width="wrap_content"
          android:layout_height="match_parent"
          android:layout_gravity="center_vertical"
          android:orientation="vertical">
    </RadioGroup>
 </LinearLayout>

这里输入图像描述

注意: 您可以自定义对话框视图(如设置标题、消息等)。

编辑: 要检索所选 RadioButton 的值,必须为您的 RadioGroup 实现 setOnCheckedChangeListener 监听器,如下所示:

 rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                 int childCount = group.getChildCount();
                 for (int x = 0; x < childCount; x++) {
                    RadioButton btn = (RadioButton) group.getChildAt(x);
                    if (btn.getId() == checkedId) {
                         Log.e("selected RadioButton->",btn.getText().toString());

                    }
                 }
            }
        });

我认为对于他的使用情况来说,创建自定义对话框似乎有点过度。但肯定仍然是一种可能性。 - JoxTraex
检查编辑以获取所选单选按钮的值。 - Rustam

9
这对我有用:
final CharSequence[] items = {"Option-1", "Option-2", "Option-3", "Option-4"};

AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
builder.setTitle("Alert Dialog with ListView and Radio button");
builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
 Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});

builder.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
  }
 });
builder.setNegativeButton("No",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
  }
 });
AlertDialog alert = builder.create();
alert.show();

9
一种简洁的方法如下所示: http://developer.android.com/guide/topics/ui/dialogs.html 摘自(添加一个持久的多选或单选列表):
mSelectedItems = new ArrayList();  // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
       .setMultiChoiceItems(R.array.toppings, null,
                  new DialogInterface.OnMultiChoiceClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which,
                   boolean isChecked) {
               if (isChecked) {
                   // If the user checked the item, add it to the selected items
                   mSelectedItems.add(which);
               } else if (mSelectedItems.contains(which)) {
                   // Else, if the item is already in the array, remove it 
                   mSelectedItems.remove(Integer.valueOf(which));
               }
           }
       })
// Set the action buttons
       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int id) {
               // User clicked OK, so save the mSelectedItems results somewhere
               // or return them to the component that opened the dialog
               ...
           }
       })
       .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int id) {
               ...
           }
       });

return builder.create();

阅读有关http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setSingleChoiceItems(int, int, android.content.DialogInterface.OnClickListener)的内容。

不需要自定义视图。


好的,作者提到了自定义。 - user924

6

Kotlin版本:

fun dialog() {
    val options = arrayOf("option1", "option2")
    var selectedItem = 0
    val builder = AlertDialog.Builder(this)
    builder.setTitle("Select an option")
    builder.setSingleChoiceItems(options
            , 0, { dialogInterface: DialogInterface, item: Int ->
        selectedItem = item
    })
    builder.setPositiveButton(R.string.accept, { dialogInterface: DialogInterface, p1: Int ->
        Toast.makeText(getApplicationContext(),
                "selected item = " + options[selectedItem], Toast.LENGTH_SHORT).show();
        dialogInterface.dismiss()
    })
    builder.setNegativeButton(R.string.cancel, { dialogInterface: DialogInterface, p1: Int ->
        dialogInterface.dismiss()
    })
    builder.create()
    builder.show();
}

1

请检查。 这是您应在CustomAdapter中使用的自定义行对话框dialog_row.xml:

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

    <RadioButton
       android:id="@+id/list"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    </LinearLayout>

然后在 onclick 方法中:
@Override
public void onClick(View arg0) {

    // custom dialog
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom_layout); //Your custom layout
    dialog.setTitle("Title...");


    Listview listview= (ListView) dialog.findViewById(R.id.listview);

    CustomAdapter adapter=new CustomAdapter(context,your_list);
    listview.setadapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Do something

        }
    });

    dialog.show();
}

教程链接


0
当你想要从SQLite数据库中显示数据时,
private void showRadioButtonDialog() {

    // custom dialog
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.radiobutton_dialog);
    List<String> stringList=new ArrayList<>();  // here is list 

    if (cursor.moveToFirst()) {
        do {
            String a=( cursor.getString(0).toString());
            String b=(cursor.getString(1).toString());
            String c=(cursor.getString(2).toString());
            String d=(cursor.getString(3).toString());
            stringList.add(d);
        } while (cursor.moveToNext());        
    }   

    RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group);

    for(int i=0;i<stringList.size();i++) {
        RadioButton rb=new RadioButton(this); // dynamically creating RadioButton and adding to RadioGroup.
        rb.setText(stringList.get(i));
        rg.addView(rb);
    }

    dialog.show();

    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

         @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
             int childCount = group.getChildCount();
             for (int x = 0; x < childCount; x++) {
                 RadioButton btn = (RadioButton) group.getChildAt(x);
                 if (btn.getId() == checkedId) {
                     Toast.makeText(getApplicationContext(), btn.getText().toString(), Toast.LENGTH_SHORT).show();
                 }
             }
         }
     });
}

0
在安卓中使用Jetpack Compose -
AlertDialog(onDismissRequest = { viewModel.shouldDialogOpen.value = false },

            title= { "title" },
            text = {
                Column {
                    Text(
                        text = "Filter by Title Or Date",
                        modifier = Modifier.fillMaxWidth(),
                        color = Color.Black,
                        fontSize = 16.sp
                    )
                    Spacer(modifier = Modifier.height(16.dp))

                    radioOptions.forEach { text ->
                        Row(
                            Modifier
                                // using modifier to add max
                                // width to our radio button.
                                .fillMaxWidth()
                                // below method is use to add
                                // selectable to our radio button.
                                .selectable(
                                    // this method is called when
                                    // radio button is selected.
                                    selected = (text == viewModel.selectedFilter.value),
                                    onClick = { viewModel.onFilterSelected(text) }
                                    // below method is called on
                                    // clicking of radio button.
                                )
                                // below line is use to add
                                // padding to radio button.
                                .padding(horizontal = 16.dp),
                            verticalAlignment = Alignment.CenterVertically

                        ) {
                            // below line is use to get context.

                            // below line is use to
                            // generate radio button
                            RadioButton(
                                // inside this method we are
                                // adding selected with a option.
                                selected = (text == viewModel.selectedFilter.value),
                                onClick = {
                                    // inide on click method we are setting a
                                    // selected option of our radio buttons.
                                    viewModel.onFilterSelected(text)

                                },
                                modifier = Modifier
                                    .padding(top = 16.dp)
                                    .alignBy(FirstBaseline)

                            )
                            // below line is use to add
                            // text to our radio buttons.
                            Text(
                                text = text,
                                style = MaterialTheme.typography.body1.merge(),
                                modifier = Modifier
                                    .padding(top = 16.dp)
                                    .alignBy(FirstBaseline)
                            )
                        }
                    }

                }
            },


            confirmButton = {
                Button(modifier = Modifier.fillMaxWidth(), onClick = {
                    viewModel.shouldDialogOpen.value = false
                }) {
                    Text(text = "OKay")
                }
            }
        )

这里的radioOptions是用于单选按钮标签/文本的字符串列表。

viewModel.shouldDialogOpen是viewmodel内可变状态字段,其值在需要显示或关闭对话框时更改。

有关Jetpack Compose的更多代码示例,请参阅此处- https://androidlearnersite.wordpress.com/2021/08/03/jetpack-compose-1-0-0-sample-codes/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接