如何在Android

时间:2015-10-18 01:14:01

标签: java android

我想在Activity中单击其中一个片段后,在自定义对话框中设置TextView的值。在调用后,Dialog在自定义文本视图中运行正常。问题是当我尝试调用 changeMes​​sageText(" Hello")函数时,它总是显示 NullPointerException

ProgressDialogFragment.java

public class ProgressDialogFragment extends DialogFragment {

        private TextView txtMessage;
        private AlertDialog.Builder mBuilder;

        public static ProgressDialogFragment newInstance(AlertDialog.Builder builder){
            ProgressDialogFragment progressDialogFragment = new ProgressDialogFragment();
            progressDialogFragment.mBuilder = builder;
            return progressDialogFragment;
        }

        @Nullable
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);
            txtMessage = (TextView) view.findViewById(R.id.txtMessage);

            changeMessageText("Hello World by default"); // this one works

            mBuilder.setView(view);

            return mBuilder.create();

        }
        public void changeMessageText(String text){
            txtMessage.setText(text);
        }
}
单击按钮后

示例代码

AlertDialog.Builder builder = new AlertDialog.Builder(this);
ProgressDialogFragment progressDialogFragment = ProgressDialogFragment.newInstance(builder);
progressDialogFragment.show(getSupportFragmentManager(),"progress_dialog");
// dialog box shows until the following function is called.

progressDialogFragment.changeMessageText("Hello");

1 个答案:

答案 0 :(得分:2)

调用progressDialogFragment.changeMessageText("Hello");时,尚未创建txtMessage

1)将private String message;添加到ProgressDialogFragment

2)更改changeMessageText

public void changeMessageText(String text){
    message = text;
    if(txtMessage != null){
        txtMessage.setText(text);
   }            
}

3)在mBuilder.setView(view);

之后添加
if(message!=null && !message.isEmpty()){
    txtMessage.setText(message);
}

4)删除changeMessageText("Hello World by default");

中的onCreateDialog

和。它对我不起作用。

View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);

我改变它。

LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_progress, null);

希望它会对你有所帮助。