【发布时间】:2021-03-23 12:30:35
【问题描述】:
我正在使用 DialogFragment 并调用 onViewCreated,但是卡片视图不会更新其不透明度。
我的代码应该禁用未选中的卡片视图并将其变灰,但没有任何变化。 我尝试将代码放在 onCreateView 中,但效果不佳。
class AddBookDialogFragment: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
// Get the layout inflater
val inflater = requireActivity().layoutInflater
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_add_book, null))
// Add action buttons
.setPositiveButton("Create") { dialog, id ->
// create the book
}
.setNegativeButton("Cancel") { _, _ ->
dialog?.cancel()
}
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val addBookRadioGroup: RadioGroup = view.findViewById(R.id.add_book_radio_group)
view.findViewById<RadioButton>(R.id.isbn_radio_button).isEnabled = true
addBookRadioGroup.setOnCheckedChangeListener { _, checkedId ->
// checkedId is the RadioButton selected
val manualCardView: CardView = view.findViewById(R.id.manual_card_view)
val isbnCardView: CardView = view.findViewById(R.id.isbn_card_view)
var disabledCardView: CardView = manualCardView
var enabledCardView: CardView = isbnCardView
// Sets which card view will be enabled / disabled
when (checkedId) {
R.id.isbn_radio_button -> {
disabledCardView = manualCardView
enabledCardView = isbnCardView
}
R.id.manual_card_view -> {
disabledCardView = isbnCardView
enabledCardView = manualCardView
}
}
disabledCardView.isEnabled = false
// Sets opacity to 60%
disabledCardView.alpha = 0.6F
enabledCardView.isEnabled = true
// Sets to opacity to 100%
enabledCardView.alpha = 1F
}
}
// On create view must be overridden here so that it does not return null, if it returns null onViewCreated won't run
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return layoutInflater.inflate(R.layout.dialog_add_book, container, false)
}
}
我的 xml 文件的结构是这样的
<ConstraintLayout>
<RadioGroup>
<RadioButton>
<CardView>
some TextInputEditTexts to input fields
</CardView>
<RadioButton>
<CardView>
some TextInputEditTexts to input fields
</CardView>
</RadioGroup>
</ConstraintLayout>
这是我显示 DialogFragment 的方式
activity?.supportFragmentManager?.let { it ->
AddBookDialogFragment().show(it, "Add Book")
}
【问题讨论】: