Пользовательский ListViewAdapter с переключателями.

Я кодирую listView, который получает данные с сервера mySQL. Я создал следующие классы. Класс ListView. У него есть два подрядчика, все в Strings. А я сидел геттерами и сеттерами. Я считаю, что у меня проблема с самим адаптером. Я могу выбрать более одного варианта. Хотя я создал пользовательский адаптер в макете следующим образом:

<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/RG_Adapter"
    android:layoutDirection="rtl"
    android:orientation="horizontal">
    <RadioButton
        android:id="@+id/TRIP_NAME"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:textAlignment="center"
        android:textSize="25sp"
        android:textColor="#000000"
        />

    <TextView
        android:id="@+id/SUM_TRIPS"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="#000000"
        android:textAlignment="center"
        android:textSize="25sp" />

</RadioGroup>

Я считаю, что моя проблема связана с классом адаптера.

Я создал его следующим образом:

  public class TRIPS_LISTVIEW_ADAPTER extends ArrayAdapter<TRIPS_LISTVIEW> {
private Context mContext;
private ArrayList<TRIPS_LISTVIEW> mData;
private MyFunctionsClass myFunctionsClass = new MyFunctionsClass();

public TRIPS_LISTVIEW_ADAPTER (Context mContext, ArrayList<TRIPS_LISTVIEW> mData) {
    super(mContext, R.layout.summary_shape_layout,mData);
    this.mContext = mContext;
    this.mData = mData;
}


public int getCount() {
    return mData.size();
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    if (convertView == null)
    {
        LayoutInflater mInflater = (LayoutInflater)
                mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.summary_shape_layout, null);
    }
    RadioGroup RG = (RadioGroup) convertView.findViewById(R.id.RG_Adapter);
    TextView TRIP_NAME = (TextView) convertView.findViewById(R.id.TRIP_NAME);
    TRIP_NAME.setTypeface(myFunctionsClass.FONT( TRIP_NAME.getContext().getAssets(),1));
    TRIP_NAME.setText(myFunctionsClass.get_The_trip(mData.get(position).getTRIP_TITLE()));
    TextView SUM_TRIPS = (TextView) convertView.findViewById(R.id.SUM_TRIPS);
    SUM_TRIPS.setTypeface(myFunctionsClass.FONT( SUM_TRIPS.getContext().getAssets(),1));
    SUM_TRIPS.setText(mData.get(position).getTRIP_COUNT());
    return convertView;
}

}

Данные в моем классе MainActivity извлекаются правильно. Но, как я уже упоминал, у меня есть выбор нескольких режимов. введите здесь описание изображения


person Amjad AL-Ahdal    schedule 16.08.2018    source источник
comment
надеюсь мой вопрос понятен   -  person Amjad AL-Ahdal    schedule 16.08.2018
comment
Только радиокнопки, которые находятся в одной радиогруппе, ограничены в том смысле, что вы можете выбрать только 1. У вас есть отдельная радиогруппа для каждого элемента в списке, что означает, что все радиокнопки могут быть выбраны.   -  person Tim    schedule 16.08.2018
comment
О, так что я должен указать, что родительское представление RadioButton и TextView является RadioGroup. Правильный?   -  person Amjad AL-Ahdal    schedule 16.08.2018
comment
нет, это уже так. Вы можете реализовать что-то в адаптере, чтобы отслеживать, какой переключатель выбран, и отменять выбор всех остальных при выборе нового.   -  person Tim    schedule 16.08.2018


Ответы (1)


Попробуйте следующее:

1) Демо2.класс: --------------

public class Demo2 extends AppCompatActivity {

private ListView lv;
private CheckBox cb;
private Adapter adapter;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo2);

    checkBoxState = new ArrayList<>();
    checkBoxText = new ArrayList<>();

    for(int i = 0 ; i<10 ; i++){
        if(i == 0) {
            checkBoxState.add(i, true);
        }else{
            checkBoxState.add(i , false);
        }
        checkBoxText.add( i , "C" + (i+1));
    }

    lv = (ListView) findViewById(R.id.lv);
    adapter = new Adapter(getApplicationContext() , checkBoxState , checkBoxText);
    lv.setAdapter(adapter);


}
}

2) Класс адаптера: -------

public class Adapter extends BaseAdapter {

private Context context;
private LayoutInflater layoutInflater;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;

public Adapter(Context context, List<Boolean> checkBoxState , List<String> checkBoxText) {

    this.context = context;

    layoutInflater = LayoutInflater.from(context);

    this.checkBoxState = checkBoxState;

    this.checkBoxText = checkBoxText;

}


public int getCount() {
    return checkBoxState.size();
}

public Object getItem(int position) {
    return checkBoxState.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {

    View view = convertView;
    final CheckBox cb_list_item;

    if (convertView == null) {
        if (layoutInflater != null) {
            view = layoutInflater.inflate(R.layout.list_item, null);
        }
    }

    cb_list_item = (CheckBox) view.findViewById(R.id.cb_list_item);
    cb_list_item.setText(checkBoxText.get(position));
    cb_list_item.setOnCheckedChangeListener(null); // mask onCheckedChangeListener()
    cb_list_item.setChecked(checkBoxState.get(position));
    cb_list_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (!b) { // already selected
                compoundButton.setChecked(true);
            } else { // is selected now
                checkSelected(position);
            }
        }
    });

    return view;
}


private void checkSelected(int position){
    try {
        for (int i = 0; i < checkBoxState.size(); i++) {
            checkBoxState.set(i, false);
        }
        checkBoxState.set(position, true);
        this.notifyDataSetChanged();
    }catch (Exception e){
        e.printStackTrace();
    }
}
}

3) demo2.xml: -------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="vertical">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lv"
    android:layout_marginStart="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp">
</ListView>

</LinearLayout>

4) list_item.xml: -----------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="C"
    android:layout_marginStart="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/cb_list_item"/>

</android.support.constraint.ConstraintLayout>

5) Выход: ---------

Вывод

person Brainnovo    schedule 16.08.2018