#android #listview #android-alertdialog
#Android #ListView #Android-AlertDialog
Вопрос:
Я создал диалоговое окно оповещения, в котором отображается список адресов, которые искал пользователь. Однако, когда отображается диалоговое окно предупреждения с элементами списка, я получаю повторение одного и того же элемента, поэтому, если у меня есть 6 адресов, я получу элемент 3 в коллекции адресов, повторяющийся 6 раз.
Я отладил, и в коллекции адресов отображаются уникальные элементы, однако что-то идет не так между созданием диалогового окна и настройкой адаптера для listview. Я думаю, что это как-то связано с convertView в классе AddressRowAdapter, но я не слишком уверен.
Вот этот код.
Это класс SearchLocation, resource_address_listview содержит виджет ListView, который находится в RelativeLayout
//set our adapter
AddressRowAdapter dataAdapter = new AddressRowAdapter(getActivity(), addressList);
//Create Address Selection Dialog
AlertDialog.Builder addressSelectionDialog = new AlertDialog.Builder(getActivity());
//Get the layout file
LayoutInflater alertDialogInflater = getActivity().getLayoutInflater();
//Get our custom view
View getAlertDialogView = alertDialogInflater.inflate(R.layout.resource_address_listview,null);
//Set our custom view
addressSelectionDialog.setView(getAlertDialogView);
//Set up, confirmation buttons and events for dialog
addressSelectionDialog.setPositiveButton("Select", new AlertDialogPositiveButtonClick());
addressSelectionDialog.setNegativeButton("Cancel", new AlertDialogCancelButtonClick());
//Set up our adapter
//Get our list view
listViewAddressList = (ListView)getAlertDialogView.findViewById(R.id.listViewAddressList);
listViewAddressList.setAdapter(dataAdapter);
//listViewAddressList.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//Single choice mode, radio buttons
listViewAddressList.setOnItemClickListener(new AddressListViewOnItemClick());//Set our item click listener.
//Create and show dialog
createDialog = addressSelectionDialog.create();
createDialog.show();
Вот код для AddressRowAdapter, я считаю, что что-то здесь не так, но я не вижу ничего плохого в коде.
общедоступный класс AddressRowAdapter расширяет ArrayAdapter {
//Initialize private variables.
private Context context;
private List<Address> addresses;
private LayoutInflater inflater;
public AddressRowAdapter(Context context, List<Address> objects) {
super(context, 0, objects);
this.context = context;
this.addresses = objects;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Setup location variables.
String _county = "";
String _subCounty = "";
String _country = "";
String _countryCode = "";
String _postcode = "";
String _addressLine="";
String _seperator = " ";
String _comma = ",";
//If no view is provided, get the view
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.select_dialog_singlechoice, parent, false);
}
//Find all controls in view.
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
//loop through all the addresses.
for (int i=0;i<addresses.size();i )
{
//Get address.
Address thisAddress = addresses.get(i);
//if it has no long/lat coordinates we do not need it.
if (!thisAddress.hasLatitude() amp;amp; !thisAddress.hasLongitude())
break;
if (thisAddress.getAddressLine(0) != null)
_addressLine = thisAddress.getAddressLine(0) _seperator;
if (thisAddress.getAdminArea() != null)
_county=thisAddress.getAdminArea() _comma;
if(thisAddress.getSubAdminArea() != null)
_subCounty=thisAddress.getSubAdminArea() _seperator;
if (thisAddress.getPostalCode() != null)
_postcode = thisAddress.getPostalCode() _seperator;
if (thisAddress.getCountryCode() != null)
_countryCode=thisAddress.getCountryCode() _comma;
if (thisAddress.getCountryName() != null)
_country = thisAddress.getCountryName();
textView.setText(_addressLine _county _subCounty _postcode _countryCode _country);
}
return convertView;
}
@Nullable
@Override
public Address getItem(int position) {
return addresses.get(position);
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public int getCount() {
return addresses.size();
}
}
Я отлаживал это бесчисленное количество раз, и в коллекции адресов всегда отображаются уникальные элементы, и я, похоже, не перезаписываю / не заменяю их, поэтому я полностью потерян для того, что происходит.
Любая помощь будет оценена
С уважением
Комментарии:
1. добавить AddressRowAdapter полный код
Ответ №1:
Почему вы используете цикл for в адаптере? Цикл for не нужен. Вы можете напрямую использовать
Address thisAddress = addresses.get(position);
Адаптер создаст представление для количества счетчиков, возвращаемых методом getCount(). Таким образом, если вы возвращаете правильное количество, оно автоматически создаст представление для всех адресов.
public int getCount(){
return addresses.size();
}
Комментарии:
1. Спасибо, да, мне не нужен был цикл, и это, кажется, решило проблему.