问题描述
我有一个带有 3 个单选按钮的单选组。当我点击单选按钮时,动画正在改变,但 oncheckedchangelistener
没有被调用。没有任何日志正在打印,所以我认为它一定是侦听器,但我看不出任何错误。我遵循了几个例子,但一切都几乎相同。这是我的代码:
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
viewmodel.myTracksShort.observe(viewLifecycleOwner) { state ->
when (state) {
is DataState.Success -> {
shortList = state.data.items!!
if (checkedRadioButton == 0){
mostListenedAdapter.setTracksList(shortList)
}
setScreenToSuccess()
}
is DataState.Fail -> {
}
}
}
viewmodel.myTracksMedium.observe(viewLifecycleOwner) { state ->
when (state) {
is DataState.Success -> {
mediumList = state.data.items!!
setScreenToSuccess()
}
is DataState.Fail -> {
}
}
}
viewmodel.myTracksLong.observe(viewLifecycleOwner) { state ->
when (state) {
is DataState.Success -> {
longList = state.data.items!!
setScreenToSuccess()
}
is DataState.Fail -> {
}
}
}
binding.rg.setonCheckedchangelistener {
group,checkedId ->
Log.d(TAG,"onViewCreated: $checkedId")
when (checkedId) {
R.id.rb1 -> {
Log.d("TAG","onViewCreated: short")
if (this::shortList.isInitialized) {
mostListenedAdapter.setTracksList(shortList)
checkedRadioButton = 0
}
}
R.id.rb2 -> {
if (this::mediumList.isInitialized) {
Log.d("TAG","onViewCreated: m")
mostListenedAdapter.setTracksList(mediumList)
checkedRadioButton = 1
}
}
R.id.rb3 -> {
if (this::longList.isInitialized) {
Log.d("TAG","onViewCreated: l")
mostListenedAdapter.setTracksList(longList)
checkedRadioButton = 2
}
}
else -> Log.d(TAG,"onViewCreated: else")
}
}
还有我的 XML 文件:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="@+id/rg"
android:weightSum="9"
android:checkedButton="@id/rb1"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="@color/colorPrimary">
<RadioButton
android:layout_width="0dp"
android:layout_height="30dp"
android:id="@+id/rb1"
android:layout_weight="3"
android:text="@string/short_term"
android:gravity="center"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:textColor="@color/radio_flat_text_selector"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="30dp"
android:id="@+id/rb2"
android:gravity="center"
android:layout_weight="3"
android:text="@string/mid_term"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:textColor="@color/radio_flat_text_selector"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="30dp"
android:id="@+id/rb3"
android:gravity="center"
android:layout_weight="3"
android:text="@string/long_term"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:textColor="@color/radio_flat_text_selector"/>
</RadioGroup>
解决方法
对于任何反击相同错误的人:我将我的 Radio Group 的 ID 重命名为 radioGroup 并解决了。