如何在单击“确定”按钮单击文本输入对话框时获取字符串值?

时间:2012-01-23 07:56:33

标签: android click onclick

我创建了一个函数taketext(),它在文本输入对话框中返回输入文本的字符串值。下面是代码(显然不正确)。我希望这只在单击“确定”按钮时返回字符串。如果删除'if',则它始终返回null。此takeText()方法由另一个方法调用。

private String takeText() {
    String text = null;
    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.text_tag, null);
    final DialogWrapper wrapper = new DialogWrapper(addView);

    new AlertDialog.Builder(this)
            .setTitle("Enter Text")
            .setView(addView)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // processAdd(wrapper);
                    // text = wrapper.getData();
                    okBClicked = true;

                }
            })
            .setNegativeButton("cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            // ignore, just dismiss
                        }
                    }).show();
    if (okBClicked)
        return wrapper.getData();
    else
    //???
}

1 个答案:

答案 0 :(得分:0)

不要让你的方法返回字符串。对其进行编码以显示输入字符串的弹出窗口。稍后,您必须引用R.layout.text_tag中定义的EditText并在PositiveButton的click事件中获取其值。例如:

String text = null;

private void popToTakeText() {
    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.text_tag, null);

    EditText txtBox = addView.findViewById(R.id.my_edit_text_box);

    final DialogWrapper wrapper = new DialogWrapper(addView);

    new AlertDialog.Builder(this)
            .setTitle("Enter Text")
            .setView(addView)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // processAdd(wrapper);
                    // text = wrapper.getData();
                    okBClicked = true;
                    text = txtBox.getText();

                }
            })
            .setNegativeButton("cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            // ignore, just dismiss
                        }
                    }).show();

}