安卓AlertDialog设置文本

3

大家好,我有一个AlertDialog,在Listview中点击某个项目后会创建。我试图从我的活动(activity)中获取文件名、描述、作者等信息,并在我的AlertDialog中显示它们,但是setText无法工作。请问有谁可以帮忙解决?感谢您!这是我的代码: http://pastebin.com/FzWSPp5e

1个回答

1

这绝不是在Android中正确使用对话框的方式。您需要在onCreateDialog的覆盖方法中定义对话框,就像在文档中所描述的那样:

http://developer.android.com/guide/topics/ui/dialogs.html

按照这个指南,您应该能够解决您的问题。这里是一个我刚从一个随机应用程序中复制并粘贴的示例:

@Override
protected Dialog onCreateDialog(int id, Bundle b) {
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
    AlertDialog.Builder builder = null;
    switch(id) {
        case DIALOG_BLOCK_SIZE:
        {
            Dialog dialog = new Dialog(this);
            final View dialogLayout = inflater.inflate(R.layout.dialog_block_size, null);
            builder = new AlertDialog.Builder(this);
            builder.setView(dialogLayout);
            builder.setTitle("Set Block Size");

            final EditText blockIn = (EditText)dialogLayout.findViewById(R.id.block_size_in);
            blockIn.setText(new Integer(pref.getInt("block_size", 6)).toString());

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        SharedPreferences.Editor editor = pref.edit();
                        editor.putInt("block_size", new Integer(blockIn.getText().toString()));
                        editor.commit();
                        ////////TODO///////////
                        //notify MinutemaidService that we have changed the block_size
                        dialog.dismiss();
                    }
                });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
            dialog = builder.create();
            return dialog;
        }
        default:
        {
            return null;
        }
    }
    return dialog;
}

使用上述代码,您可以调用showDialog(DIALOG_BLOCK_SIZE)来显示对话框。还要注意,对话框只创建一次,然后反复显示。要强制重建对话框,请在调用showDialog(int)之前调用removeDialog(int)。覆盖onPrepareDialog()是最佳方法,但使用removeDialog也可以,并且更容易。

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