У меня есть настраиваемый список, который содержит радиокнопку и текстовое представление. Когда я выбираю 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>
Прямо сейчас ваши переключатели являются частью разных макетов. Поскольку вы не используете 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>
Вы разместили переключатель на каждом элементе представления списка, они не связаны друг с другом, поскольку они не находятся в одном и том же 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;
Комментарии не для расширенного обсуждения; этот разговор был перешел в чат.
Я отредактировал свой код, как вы предлагаете, но я все еще сталкиваюсь с той же проблемой