簡體   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