【问题标题】:Showing custom view inside AlertDialog在 AlertDialog 中显示自定义视图
【发布时间】:2014-03-13 18:42:19
【问题描述】:

我有一个扩展 LinearLayout 的类。它只包含两个EditBox。单击某些按钮时,我想在警报对话框中加载此类。当我单击按钮时,会显示警报对话框,但不会显示扩展 LinearLayout 的视图类。代码如下。我陷入了困境。我能得到一些解决方案吗??

public class StudentDialog extends LinearLayout {
    Context context;
    LinearLayout layout;

    public StudentDialog(Context context) {
        super(context);
        this.context = context;
        createStudentDialog();
    }

    private void createStudentDialog() {

        layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        layout.setPadding(10, 10, 10, 10);
        layout.setId(200);

        EditText studentName = new EditText(context);
        studentName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        studentName
                .setTextAppearance(getContext(), TEXT_DIRECTION_FIRST_STRONG);

        EditText address = new EditText(context);
        address.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        address.setTextAppearance(getContext(), TEXT_DIRECTION_FIRST_STRONG);

        layout.addView(studentName);
        layout.addView(address);

    }

}

//Now i am calling this on some button click listener as follows. The alert dialog is displayed but not the StudentDialog. 

StudentDialog dialog = new StudentDialog(this);



        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setView(dialog);

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

【问题讨论】:

标签: java android android-alertdialog android-custom-view


【解决方案1】:

如果你改变它应该可以工作

alertDialogBuilder.setView(dialog);

作为

alertDialogBuilder.setView(dialog.layout);

【讨论】:

  • 或者您可以从 StudentDialog 类中删除“布局”变量,因为它已经是一个线性布局。您可以从 createStudentDialog 函数内部将视图添加到“this”。然后它将按预期工作。您在原始代码中所做的是将editTexts 添加到一个布局中,并将不同的布局添加到AlertDialog。
【解决方案2】:

您是否想在警报视图中显示两个编辑文本,就像带有按钮的登录对话框一样,如果是,那么只需创建一个您想在对话框视图中显示的布局。创建一个扩展 Dialog 的类,并在此类的 onCreate 的 setContentView 中设置此布局

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多