Я разработал сценарий, который, согласно моему пониманию Java, должен был хорошо работать, но, к сожалению, этого не произошло. Сценарий объясняется в коде:Android - Получить значения кнопок радио в ListView
ListViewAdapter
public final class ListViewAdapter extends BaseAdapter {
private Context context;
private RadioGroup[] radioGroups;
private List<String> listOfData;
public OneForAllListViewAdapter(Context context, List<String> listOfData) {
super();
this.context = context;
this.radioGroups = new RadioGroup[listOfData.size()];
this.listOfData = listOfData;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final String timelyOfferedStr = "Yes";
final String lateOfferedStr = "Yes but late";
final String notOfferedStr = "No";
final String pName = listOfData.get(position);
if(convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.one_for_all_list_item, parent, false);
}
TextView pNameTextView = (TextView) convertView.findViewById(R.id.one_for_all_p_name_TextView);
RadioButton timelyOffered = (RadioButton) convertView.findViewById(R.id.one_for_all_timely_offered);
RadioButton lateOffered = (RadioButton) convertView.findViewById(R.id.one_for_all_late_offered);
RadioButton notOffered = (RadioButton) convertView.findViewById(R.id.one_for_all_not_offered);
this.radioGroups[position] = (RadioGroup) convertView.findViewById(R.id.one_for_all_radio_group);
pNameTextView.setText(pName);
timelyOffered.setText(timelyOfferedStr);
lateOffered.setText(lateOfferedStr);
notOffered.setText(notOfferedStr);
return convertView;
}
@Nullable
public ThatStatus[] getThoseStatuses()
{
ThatStatus[] thoseStatuses = new ThatStatus[radioGroups.length];
for(int i=0; i<radioGroups.length; i++) {
int selectedRadioButton = radioGroups[i].getCheckedRadioButtonId();
switch (selectedRadioButton) {
case R.id.one_for_all_timely_offered:
thoseStatuses [i] = ThatStatus.TimelyOffered;
break;
case R.id.one_for_all_late_offered:
thoseStatuses [i] = ThatStatus.Offered;
break;
case R.id.one_for_all_not_offered:
thoseStatuses [i] = ThatStatus.NotOffered;
break;
default:
return null;
}
}
return thoseStatuses;
}
}
Важно отметить в выше коде эта линия:
this.radioGroups[position] = (RadioGroup) convertView.findViewById (R.id.one_for_all_radio_group);
Я спасаю все RadioGroup
с в массив RadioGroup
, и в getThoseStatuses()
Я пытаюсь получить проверенные RadioButton
s от тех RadioGroup
s. Но radioGroups[i].getCheckedRadioButtonId()
всегда возвращает мне -1.
Я пропустил некоторые концепции Java? В чем проблема?
Я извиняюсь за поздний ответ, как это отличается от моего решения? Вы создаете дополнительный класс для сохранения просмотров, я сохраняю их в массиве. –
Это не просто класс для хранения данных. Ваш код может часто вызвать findViewById() во время прокрутки ListView, что может замедлить производительность. Даже когда адаптер возвращает завышенный вид для повторной переработки, вам все равно нужно искать элементы и обновлять их. Способом повторного использования findViewById() является использование шаблона дизайна «view holder». –
хорошо, спасибо за объяснение производительности. Я попробую. –