安卓中的单选选择对话框

6

我正在制作一个安卓程序。在我的应用中,我正在使用单选选择AlertDialog,其项目是通过编程添加的。我想做的是:

  • 下次用户打开对话框时为所选项目设置背景颜色,
  • 在对话框中间显示所选项目(这是一个问题,因为大约有20个项目)。

以下是我的XML代码:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dp" >



    <Button
        android:id="@+id/selectDateButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please, select date" />

</LinearLayout>

JAVA:

public class ExperimentListView extends Activity {

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static Calendar calendar = Calendar.getInstance();
private static Button selectDateButton;
private static String[] items;
private static int selectedDatePosition = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_view_ex);

    selectDateButton = (Button)findViewById(R.id.selectDateButton);
    selectDateButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            items = new String[20];
            for (int i = 0; i < 20; i++) {
                items[i] = DATE_FORMAT.format(calendar.getTime());
                calendar.add(Calendar.DATE, 1);
            }
            showListView();
        }
    });

}

private void showListView() {
    AlertDialog.Builder builder = new AlertDialog.Builder(ExperimentListView.this);
    builder.setTitle("Select date");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            selectedDatePosition = which;
            selectDateButton.setText(items[selectedDatePosition]);
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.getListView().setSelection(selectedDatePosition);
    alertDialog.show();
 }
}

到目前为止,我还没有找到解决方案,如果有人能帮忙,我将不胜感激。 提前致谢。

2个回答

2

不要使用builder.setItem,而是使用builder.setSingleChoiceItems并将所选项目位置作为参数传递,例如:

    builder.setSingleChoiceItems(strArray, selected_pos, new DialogInterface.OnClickListener ()
    {
         @Override
         public void onClick(DialogInterface dialog, int which) 
         {

         }
    });

单选对话框似乎无法满足我的需求,因为有一个点我自定义的风格不支持。这就是为什么我没有使用它的原因。 - boburShox
我在应用程序中使用了单选,但我很想知道是否有人找到了解决方案。 - boburShox

1

1)要设置背景颜色,您可以为警报对话框使用自定义视图

2)要在对话框中间显示所选项目,您需要交换其在数组中的位置,该数组是传递给警报对话框列表的。

3)如果您希望背景颜色与先前选择的项目相关,请使用共享首选项存储项目和背景,并在用户打开警报对话框时重新获取背景和所选项目。

正如Deepika所说,使用setSingleChoiceItems进行单选选择。


感谢您的回复。交换的想法似乎不错,但我希望在用户没有注意到的情况下滚动到所选项目后再显示UI。3)在我的情况下,我认为不需要共享首选项,因为每次将默认文本设置为按钮。 - boburShox

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