How to use data-binding in Dialog?

前端 未结 8 1778
傲寒
傲寒 2021-01-30 12:29

I am having trouble in implementing databinding in a Dialog. Is it possible?

Below is my xml.



    

        
8条回答
  •  旧巷少年郎
    2021-01-30 12:58

    here is a full example of a AlertDialog with Databinding:

    import android.app.Dialog;
    import android.databinding.DataBindingUtil;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.DialogFragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v7.app.AlertDialog;
    import android.view.LayoutInflater;
    
    
    public class MyDialog extends DialogFragment {
    
        private static final String KEY_MY_INFO = "KEY_MY_INFO";
    
        private String myInfo;
    
        public static MyDialog newInstance(String myInfo) {
            MyDialog dialog = new MyDialog();
            Bundle bundle = new Bundle();
            bundle.putString(KEY_MY_INFO, myInfo);
            dialog.setArguments(bundle);
            return dialog;
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            myInfo = getArguments().getString(KEY_MY_INFO);
        }
    
        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            FragmentActivity activity = getActivity();
    
            MyInfoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()),
                    R.layout.my_info_dialog_layout, null, false);
    
            binding.setMyInfo(myInfo);
    
            return new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle)
                    .setView(binding.getRoot())
                    .create();
        }
    
    }
    

提交回复
热议问题