【问题标题】:How to set the value of TextView in Custom Dialog in Android如何在Android的自定义对话框中设置TextView的值
【发布时间】:2015-10-18 01:14:00
【问题描述】:

单击 Activity 中的片段之一后,我想在自定义对话框中设置 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");

【问题讨论】:

    标签: java android


    【解决方案1】:

    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) 删除onCreateDialog中的changeMessageText("Hello World by default");

    而且。它不适合我。

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

    我改了。

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

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2021-04-19
      相关资源
      最近更新 更多