Пользовательский список с радиокнопкой. Мне нужен один выбор радиокнопки из нескольких списков радиокнопок

У меня есть настраиваемый список, который содержит радиокнопку и текстовое представление. Когда я выбираю 1 радиокнопку, выбирается несколько радиокнопок. Каждые следующие 4 индексных радиокнопки также выбираются. Я хочу выбрать только 1 радиокнопку за раз.

это код адаптера

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Definition.Dto;
using static Android.Widget.CompoundButton;

namespace SGDDPortal.Android.Model
{
    public class ViewHolder : Java.Lang.Object
    {
        public TextView LabelText { get; set; }
        public RadioButton ListRadioButton { get; set; }
    }

    public class DepartmentListAdapter : BaseAdapter<DepartmentDto>, IOnCheckedChangeListener
    {
        private Activity activity;
        List<DepartmentDto> Departments;
        int selectedIndex = -1;

        public DepartmentListAdapter(Activity activity, List<DepartmentDto> Departments)
        {
            this.activity = activity;
            this.Departments = Departments;
        }

        public override DepartmentDto this[int position] => Departments[position];

        public override int Count => Departments.Count;

        public override long GetItemId(int position)
        {
            return position;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.DepartmentPopUpListViewRow, parent, false);
            var btnRadio = view.FindViewById<RadioButton>(Resource.Id.SelectedDepartment);
            btnRadio.SetOnCheckedChangeListener(null);
            btnRadio.Tag = position;
            btnRadio.Checked = Departments[position].Checked;
            btnRadio.Text = Departments[position].Afdeling_Txt;
            btnRadio.SetOnCheckedChangeListener(this);


            return view;
        }

        private void BtnRadio_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
        {
            throw new NotImplementedException();
        }

        public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
        {
            int position = (int)buttonView.Tag;
            if (isChecked)
            {
                foreach (DepartmentDto model in Departments)
                {
                    if (model != Departments[position])
                    {
                        model.Checked = false;
                    }
                    else
                    {
                        model.Checked = true;
                    }
                }
                NotifyDataSetChanged();
            }
        }
    }
}

Это код Windowpopup

private void DepartmentPicker_Click(object sender, EventArgs e)
        {
            //ViewModelInstances.DepartmentVieModel.PopUpCommand.CanExecute(this);
            ButtonNext.Visibility = ViewStates.Invisible;
            GetListView.ChoiceMode=ListView.ChoiceModeSingle;
            GetListView.Adapter = new DepartmentListAdapter(this, Departments);

            bool focusable = true;
            int width = 350;//LinearLayout.LayoutParams.WrapContent;
            int height = 450;//LinearLayout.LayoutParams.WrapContent;
                             // listView = _PopUpView.FindViewById<ListView>(Resource.Id.Departmentlistview);
            PopupWindow popupWindow = new PopupWindow(_PopUpView, width, height, focusable);
            popupWindow.ContentView = _PopUpView;
            popupWindow.ShowAtLocation(_PopUpView, GravityFlags.CenterVertical, 0, 0);
            popupWindow.Focusable = false;
            popupWindow.Touchable = true;
        } 

Это Xamal для WindowPopUp

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "vertical"
    android:layout_width = "match_parent"
    android:gravity = "center"
    android:descendantFocusability = "blocksDescendants"  
    android:layout_height = "wrap_content"
    android:background = "@android:color/background_light"
    android:weightSum = "100">
<LinearLayout
     android:orientation = "horizontal"
     android:layout_width = "match_parent"
        android:layout_weight = "10"
     android:layout_height = "40dp">
    <TextView
        android:text = "Vælg din afdeling"
        android:textSize = "20sp"
        android:textColor = "#FF222222"
        android:paddingLeft = "30dp"
        android:focusable = "false"
        android:focusableInTouchMode = "false"
        android:layout_gravity = "center"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:minWidth = "25px"
        android:minHeight = "25px"
        android:id = "@+id/textView1" />

        </LinearLayout>
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "10">
        </LinearLayout>
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "100dp"
        android:layout_weight = "50">
        <ListView
        android:minWidth = "25px"
        android:minHeight = "25px"
         android:choiceMode = "multipleChoice"
        android:focusable = "false"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:id = "@+id/Departmentlistview" />
       </LinearLayout>
     <LinearLayout
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:orientation = "horizontal"
    android:layout_marginTop = "35dp">
    <View
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        android:layout_weight = "1"/>

    <Button
        android:id = "@+id/btnAddExpense"
        android:layout_width = "wrap_content"
        android:layout_height = "45dp"
        android:textColor = "#61222222"
        android:background = "@null"
        android:text = "Annuller"
        android:layout_marginLeft = "20dp"
        android:layout_gravity = "right"
        android:layout_marginRight = "15dp" />
    <Button
        android:id = "@+id/btnok"
        android:layout_width = "wrap_content"
        android:layout_height = "45dp"
        android:textColor = "#FFF62F5E"
        android:text = "Gem"
        android:background = "@null"
        android:layout_marginLeft = "1dp" 
        android:layout_gravity = "right"
        android:layout_marginRight = "15dp" />

</LinearLayout>

</LinearLayout>

Макет xamal, который содержит переключатель и текст, когда API вызывает его, возвращает текст и связывает с этим текстом редактирования

  <?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "horizontal"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
     android:background = "@android:color/background_light" 
    android:weightSum = "100">
      <RadioGroup
        android:id = "@+id/radioGender"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" >
    <RadioButton    
            android:layout_width = "wrap_content"
            android:layout_height = "60dp"
            android:checked = "false"
            android:id = "@+id/SelectedDepartment" /> 

    </RadioGroup>
        <TextView
            android:text = "303 - Lorem ipsum"
            android:layout_weight = "50"
            android:layout_marginTop = "20dp"
            android:textColor = "#FF222222"
            android:layout_width = "wrap_content"
            android:layout_height = "60dp"
            android:id = "@+id/SelectDepartmentName" />
</LinearLayout>

Этот макет содержит ListView, который показывает данные

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "vertical"
    android:layout_width = "match_parent"
    android:gravity = "center"
    android:descendantFocusability = "blocksDescendants"  
    android:layout_height = "wrap_content"
    android:background = "@android:color/background_light"
    android:weightSum = "100">
<LinearLayout
     android:orientation = "horizontal"
     android:layout_width = "match_parent"
        android:layout_weight = "10"
     android:layout_height = "40dp">
    <TextView
        android:text = "Vælg din afdeling"
        android:textSize = "20sp"
        android:textColor = "#FF222222"
        android:paddingLeft = "30dp"
        android:focusable = "false"
         android:focusableInTouchMode = "false"
        android:layout_gravity = "center"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:minWidth = "25px"
        android:minHeight = "25px"
        android:id = "@+id/textView1" />

        </LinearLayout>
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "10">
        </LinearLayout>
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "100dp"
        android:layout_weight = "50">
        <ListView
        android:minWidth = "25px"
        android:minHeight = "25px"
         android:choiceMode = "singleChoice"
        android:focusable = "false"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:id = "@+id/Departmentlistview" />
       </LinearLayout>
     <LinearLayout
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:orientation = "horizontal"
    android:layout_marginTop = "35dp">
    <View
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        android:layout_weight = "1"/>

    <Button
        android:id = "@+id/btnAddExpense"
        android:layout_width = "wrap_content"
        android:layout_height = "45dp"
        android:textColor = "#61222222"
        android:background = "@null"
        android:text = "Annuller"
        android:layout_marginLeft = "20dp"
        android:layout_gravity = "right"
        android:layout_marginRight = "15dp" />


    <Button
        android:id = "@+id/btnok"
        android:layout_width = "wrap_content"
        android:layout_height = "45dp"
        android:textColor = "#FFF62F5E"
        android:text = "Gem"
        android:background = "@null"
        android:layout_marginLeft = "1dp" 
        android:layout_gravity = "right"
        android:layout_marginRight = "15dp" />

</LinearLayout>

</LinearLayout>
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
98
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Прямо сейчас ваши переключатели являются частью разных макетов. Поскольку вы не используете Xamarin Forms, Android предлагает использовать его для размещения всех переключателей в одной группе переключателей, как вы можете видеть ниже.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent"
    android:orientation = "vertical" >
    <RadioGroup
        android:id = "@+id/radioGender"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" >
        <RadioButton
            android:id = "@+id/radioMale"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "Male" 
            android:checked = "true" />
        <RadioButton
            android:id = "@+id/radioFemale"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "Female" />

    </RadioGroup>
    ...Other stuff in the layout...
</LinearLayout>

Я отредактировал свой код, как вы предлагаете, но я все еще сталкиваюсь с той же проблемой

Zubair Munir 12.06.2019 07:35
Ответ принят как подходящий

Вы разместили переключатель на каждом элементе представления списка, они не связаны друг с другом, поскольку они не находятся в одном и том же RadioGroup. Вы должны определить свойство в своей модели, чтобы указать, какое радио должно быть проверено.

Я имитирую вашу модель, например:

public class DepartmentDto
{
    public string Afdeling_Txt { set; get; }

    public bool Checked { set; get; }
}

И ваше событие GetView должно быть скорректировано:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.DepartmentPopUpListViewRow, parent, false);
    // var DepartmentpopUp = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.DepartmentPopUpListViewRow, parent, false);

    var btnRadio = view.FindViewById<RadioButton>(Resource.Id.SelectedDepartment);
    btnRadio.SetOnCheckedChangeListener(null);
    btnRadio.Tag = position;
    btnRadio.Checked = Departments[position].Checked;
    btnRadio.SetOnCheckedChangeListener(this);

    view.FindViewById<TextView>(Resource.Id.SelectDepartmentName).Text = Departments[position].Afdeling_Txt;
    return view;
}
public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
{
    int position = (int)buttonView.Tag;
    if (isChecked)
    {
        foreach (DepartmentDto model in Departments)
        {
            if (model != Departments[position])
            {
                model.Checked = false;
            }
            else
            {
                model.Checked = true;
            }
        }
        NotifyDataSetChanged();
    }
}

Не забудьте реализовать интерфейс IOnCheckedChangeListener в вашем адаптере: public class DepartmentListAdapter : BaseAdapter<DepartmentDto>, IOnCheckedChangeListener.

Наконец, конструктор адаптера может быть таким:

List<DepartmentDto> list = new List<DepartmentDto>();
for (int i = 0; i<10; i++)
{
    list.Add(new DepartmentDto { Checked = false, Afdeling_Txt = "item" + i });
}

DepartmentListAdapter customAdapter = new DepartmentListAdapter(this, list);
Departmentlistview.Adapter = customAdapter;

Комментарии не для расширенного обсуждения; этот разговор был перешел в чат.

Samuel Liew 13.06.2019 15:25

Другие вопросы по теме