#android #kotlin
#Android #kotlin
Вопрос:
У меня есть радиогруппа, используемая для настройки свойств класса данных, в частности сэндвича. Вот как у меня это получается до сих пор: я вручную установил видимые бутерброды, если бутерброд был отмечен, и вручную установил невидимые бутерброды, если он не был выбран. Я хочу упростить это с помощью функции, но я не уверен, как найти не выбранные идентификаторы переключателей. Я новичок как в Kotlin, так и в Android, поэтому буду признателен за любую помощь.
fun onSandwichRadioButtonClicked(view: View) {
if (view is RadioButton) {
// Is the button now checked?
val checked = view.isChecked
// Check which radio button was clicked
when (view.getId()) {
R.id.panini_button ->
if (checked) {
sandwich.sandwichCost = 7.0f
sandwich.name = "Panini"
binding.panini.visibility = View.VISIBLE
binding.hoagie.visibility = View.GONE
binding.sandwich.visibility = View.GONE
}
R.id.hoagie_button ->
if (checked) {
sandwich.sandwichCost = 10.0f
sandwich.name = "Hoagie"
binding.panini.visibility = View.GONE
binding.hoagie.visibility = View.VISIBLE
binding.sandwich.visibility = View.GONE
}
R.id.sandwich_button ->
if (checked) {
sandwich.sandwichCost = 5.0f
sandwich.name = "Sandwich"
binding.panini.visibility = View.GONE
binding.hoagie.visibility = View.GONE
binding.sandwich.visibility = View.VISIBLE
}
}
sandwich.totalCost = (sandwich.extraCost sandwich.sandwichCost).toString()
binding.invalidateAll()
Toast.makeText(
activity, "Total Cost :"
" ${sandwich.totalCost}",
Toast.LENGTH_SHORT
).show()
}
}
fun setSandwich(sandwichName: String, sandwichCost: Float, sandwichImage: ImageView){
sandwich.sandwichCost = sandwichCost
sandwich.name = sandwichName
sandwichImage.visibility = View.VISIBLE
//set the remaining sandwiches to invisible. how do I find these sandwiches?
связанный XML-код:
<ImageView
android:id="@ id/panini"
android:layout_width="192dp"
android:layout_height="79dp"
android:contentDescription="TODO"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.411"
app:srcCompat="@drawable/ic_food_obvious_panini"
tools:visibility="visible" />
<ImageView
android:id="@ id/hoagie"
android:layout_width="149dp"
android:layout_height="153dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.394"
app:srcCompat="@drawable/hoagie"
tools:visibility="gone" />
<ImageView
android:id="@ id/sandwich"
android:layout_width="140dp"
android:layout_height="311dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.345"
app:srcCompat="@drawable/ic_sandwhichanddrink"
tools:visibility="visible" />
<RadioGroup
android:id="@ id/sandwichRadioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="@ id/tomatoes_check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.88">
<RadioButton
android:id="@ id/sandwich_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSandwichRadioButtonClicked"
android:text="@string/sandwich"
android:textSize="24sp" />
<RadioButton
android:id="@ id/hoagie_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSandwichRadioButtonClicked"
android:text="@string/hoagie"
android:textSize="24sp" />
<RadioButton
android:id="@ id/panini_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSandwichRadioButtonClicked"
android:text="@string/panini"
android:textSize="24sp" />
</RadioGroup>
ОБНОВЛЕНИЕ: я немного упростил его, но я чувствую, что все еще может быть лучше. ArrayList просмотров изображений — это мой текущий обходной путь:
fun onSandwichRadioButtonClicked(view: View) {
var notChosenSandwiches: ArrayList<ImageView> = ArrayList()
if (view is RadioButton) {
// Is the button now checked?
val checked = view.isChecked
// Check which radio button was clicked
when (view.getId()) {
R.id.panini_button ->
if (checked) {
notChosenSandwiches.clear()
notChosenSandwiches.add(binding.hoagie)
notChosenSandwiches.add(binding.sandwich)
setSandwich("Panini", 7.0f, binding.panini, notChosenSandwiches)
}
R.id.hoagie_button ->
if (checked) {
notChosenSandwiches.clear()
notChosenSandwiches.add(binding.panini)
notChosenSandwiches.add(binding.sandwich)
setSandwich("Hoagie", 10.0f, binding.hoagie, notChosenSandwiches)
}
R.id.sandwich_button ->
if (checked) {
notChosenSandwiches.clear()
notChosenSandwiches.add(binding.hoagie)
notChosenSandwiches.add(binding.panini)
setSandwich("Melt", 5.0f, binding.sandwich, notChosenSandwiches)
}
}
sandwich.totalCost = (sandwich.extraCost sandwich.sandwichCost).toString()
binding.invalidateAll()
Toast.makeText(
activity, "Total Cost :"
" ${sandwich.totalCost}",
Toast.LENGTH_SHORT
).show()
}
}
/**
* update the sandwich and the views
*
* @param sandwichName the new name of the sandwich
* @param sandwichCost the new cost of the sandwich
* @param shownImage the image of the sandwich
* @param hideThese the not chosen sandwiches
*/
fun setSandwich(sandwichName: String, sandwichCost: Float, shownImage: ImageView, hideThese: ArrayList<ImageView>){
sandwich.sandwichCost = sandwichCost
sandwich.name = sandwichName
shownImage.visibility = View.VISIBLE
for (image in hideThese)
image.visibility = View.GONE
}
Комментарии:
1. вы можете получить значение нажатой кнопки переключения, а остальные в группе просмотра будут отключены … не так ли?
2. Можете ли вы опубликовать соответствующий файл XML-макета?
Ответ №1:
Ваша проблема в том, что вы знаете идентификатор выбранной кнопки и хотите иметь список всех остальных (невыбранных) Идентификаторы, чтобы вы могли сделать с ними что-то полезное?
Похоже, что это не RadioGroup
даст вам список его кнопок (только какая из них выбрана в данный момент), поэтому вам, возможно, придется сгенерировать это самостоятельно. Это подкласс LinearLayout
so, поэтому он не делает ничего сложного, просто все RadioButton
s являются прямыми дочерними элементами, так что вы можете сделать это:
sandwichButtons = sandwichRadioGroup.children
.filterIsInstance(RadioButton::class.java).toList()
что дает вам List<RadioButton>
. Или если вам просто нужны их идентификаторы:
sandwichButtonIds = sandwichRadioGroup.children
.filterIsInstance(RadioButton::class.java)
.map { it.id }
.toList()
Который является a List<Int>
со всеми их идентификаторами ( R.id.hoagie
значениями). Если вы сделаете это lateinit var
полем и назначите его с помощью поиска во onCreate
время или onViewCreated
или чего-то еще, у вас будет хороший список всех переключателей в вашей группе. Тогда вы можете сделать это:
val unselected = sandwichButtonIds.minus(selectedId)
Вероятно, есть много вещей, которые могли бы помочь в том, что вы делаете, но на данный момент я могу только догадываться, так что, надеюсь, это начало! Кроме того, «класс данных, в частности сэндвич», получает от меня одобрение