繁体   English   中英

如何在Android的“自定义对话框”中设置TextView的值

[英]How to set the value of TextView in Custom Dialog in Android

我想在“活动”中单击片段之一后,在自定义对话框中设置TextView的值。 调用对话框后,使用自定义文本视图可以正常运行该对话框。 问题是,当我尝试调用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");

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);之后添加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);

希望对您有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM