在客户警报对话框中添加复选框

时间:2013-06-11 08:03:18

标签: android

我正在尝试将复选框添加到alertdialog屏幕。我正在使用自定义xml布局来升级alertdialog usig。下面是代码。警报对话框即将出现(在我的主要活动中单击按钮),其中包含我在xml中定义的所有元素。但我没有看到对话框视图中添加了复选框。任何人都可以在这里提出建议。

    LayoutInflater factory = LayoutInflater.from(this);
    final View uploadScreenView = factory.inflate(R.layout.uploadscreen, null);
    alert = new AlertDialog.Builder(this); 
    alert.setTitle(this.getString(R.string.AlertDialog_Message_ConfirmUpload));
    alert.setView(uploadScreenView);
    String[] itemNames = getResources().getStringArray(R.array.categories_array);  
    CheckBox[] cbs = new CheckBox[itemNames.length]; 
    for (int i = 0; i < itemNames.length; i++) {
        //cb.add(new CheckBox(uploadQuizView.getContext()));
        cbs[i] = new CheckBox(uploadScreenView.getContext());
        cbs[i].setText(itemNames[i]);
    }
    //....alert.setpositive/negative button , show code here

2 个答案:

答案 0 :(得分:0)

您未将复选框“绑定”到视图中,因此不会显示它们。

你应该做的是这样的事情:

 CheckBox[] cbs = new CheckBox[itemNames.length]; 
 for (int i = 0; i < itemNames.length; i++) 
 {
        cbs[i] = new CheckBox(uploadScreenView.getContext());
        cbs[i].setText(itemNames[i]);
        uploadScreenView.addView(cbs[i]);
 }

此代码的关键是addView方法。您可以查看其documentation和此question

答案 1 :(得分:0)

下面更新了工作代码。我将uploadScreenView从View更改为ViewGroup。如果没有任何父级(已定义布局或视图组)

,则无法将子项添加到视图中
 LayoutInflater factory = LayoutInflater.from(this);
final ViewGroup uploadScreenView = factory.inflate(R.layout.uploadscreen, null);
alert = new AlertDialog.Builder(this); 
alert.setTitle(this.getString(R.string.AlertDialog_Message_ConfirmUpload));
alert.setView(uploadScreenView);
String[] itemNames = getResources().getStringArray(R.array.categories_array);  
CheckBox[] cbs = new CheckBox[itemNames.length]; 
for (int i = 0; i < itemNames.length; i++) {
           cbs[i] = new CheckBox(uploadScreenView.getContext());
    cbs[i].setText(itemNames[i]);
     uploadScreenView .addView(cbs[i]);
}
//....alert.setpositive/negative button , show code here