问题描述
我有一个对话框片段,我使用 databinding
绑定视图。
创建对话框后,我无法在文本视图上设置文本。
这是我的代码:
class MyDialogFragment : DialogFragment() {
private lateinit var layout : FragmentMyDialogBinding
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {
layout = FragmentMyDialogBinding.inflate(inflater,container,false)
return layout.root
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
layout = FragmentMyDialogBinding.inflate(LayoutInflater.from(requireContext()))
layout.textView.text = "Initial text"
layout.button.setonClickListener{
layout.textView.text = "Text changed"
Log.wtf("Text","${layout.textView.text}")
// Log shows the changed text but it is not visible on the ui.
}
val builder = MaterialAlertDialogBuilder(requireContext(),R.style.RoundShapeTheme)
builder.setView(layout.root)
return builder.create()
}
}
日志显示更改后的文本,但在 UI 上不可见。
有没有人有解决方案?
解决方法
我刚刚测试了您的代码,并通过删除 onCreateView()
解决了这个问题。您已经使用了 onCreateDialog()
,它足以设置绑定对象。
布局膨胀了两次,并且可能 textView
在未在 UI 上的布局上发生了变化。这可能是因为 onCreateView()
在 onCreateDialog()
之后被调用。因此,当您更改 onCreateDialog() 膨胀布局中的文本时,更改不会出现,因为 onCreateView()
的膨胀布局位于其顶部。
在 onCreateDialog() 方法中通过以下代码设置自定义视图:
公共对话框 onCreateDialog(@Nullable Bundle savedInstanceState) {
binding = DialogLayoutBinding
.inflate(LayoutInflater.from(getContext())); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setView(binding.getRoot());
binding.dialogTextView.setText("I am Dialog's TextView");
return builder.create(); }