从自定义对话框类中按方法访问EditText文本

时间:2018-03-09 17:11:07

标签: android alertdialog

我有这个自定义alertDialog类,我定义了一个setText()方法来设置EditText文本:

public class CustomEditDialog extends AlertDialog {

private Context context;
private CustomEditText editTextTv;
private CustomTextView titleTv;

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

public CustomEditDialog(Context context, int themeResId) {
    super(context, themeResId);
    this.context = context;
}

protected CustomEditDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
    super(context, cancelable, cancelListener);
    this.context = context;
}

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

    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    titleTv = (CustomTextView)findViewById(R.id.title_tv);
    editTextTv = (CustomEditText)findViewById(R.id.edit_text_et);


}


public void setText(CharSequence text){
    editTextTv.setText(text);
}

public String getText(){
    return editTextTv.getText().toString();
}


 }

现在,当我在activity中使用CustomEditDialog并访问setText()方法来填充edittext时:

CustomEditDialog customEditDialog = new CustomEditDialog(context);
                customEditDialog.setText("OK!!");
                customEditDialog.show();

我收到此错误:

                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'void com.k.kh.CustomEditText.setText(java.lang.CharSequence)' on a null object reference                                  

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您收到此错误是因为您在创建之前尝试调用editTextTv.setText()。 要修复它,你必须首先调用.show()来调用onCreate()并初始化CustomEditDialog视图:

CustomEditDialog customEditDialog = new CustomEditDialog(context);
            customEditDialog.show();
            customEditDialog.setText("OK!!");