【问题标题】:How to use Databinding with DialogFragment如何将数据绑定与 DialogFragment 一起使用
【发布时间】:2020-01-11 16:36:58
【问题描述】:

在我的应用程序中,我有一个由代码对象 Element 表示的项目的 ElementListFragment。我已将这些元素数据绑定到列表中,它们会显示正确的信息。 但是,为了继续填写每个项目中的信息,我在每个元素上放置了一个按钮,显示带有附加字段的Dialog。 但是当Dialog 打开时,所有字段都是空白的(至少应该填写一个),并且我填写的任何字段都不会保存数据(并且不会影响列表的更改)。

Appart 从未绑定(显示或写入)的值开始,应用程序工作正常。我基本上已经在this question 中尝试了多种不同的建议。代码如下:

public class ElementDialogFragment extends DialogFragment {
        private Element mElement;
        private Dialog dialog;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_element, null);

            final DialogSkillelementBinding binding = DialogElementBinding.inflate(LayoutInflater.from(getContext()));

            builder.setView(v)
                    // Add action buttons
                    .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            //this was just an attempt to make it work
                            binding.executePendingBindings();
                            dialog.dismiss();
                        }
                    });

            TextView Title = v.findViewById(R.id.skill_e_dialog_title);
            Title.setText(ResourceLocator.getSkillName(mElement.getSkill()));

            dialog = builder.create();
            dialog.setContentView(binding.getRoot());

            binding.setElement(mElement);
            binding.executePendingBindings();

            return dialog;
        }
    }

在调试时,我已确认 mElement 的属性正确,但它也绑定到对话框下方显示的列表。标题也显示正确。

双重绑定对象有问题吗?

函数中的某些步骤是否可能出现故障?

DialogBu​​ilder 是否与数据绑定不兼容?

【问题讨论】:

    标签: java android-databinding


    【解决方案1】:

    您应该为绑定类设置LyfecycleOwner 以进行数据更新。

    binding.setLifecycleOwner(requireActivity())
    

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 1970-01-01
      • 2018-05-23
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      相关资源
      最近更新 更多