我在DialogFragment中实现了一个listview。每个项目都有一个带有选择器的文本视图,用于模拟一个无线电组,可以选择一次只选择一个项目。
问题是当用户点击某个项目时,我正在更新适配器上的数据,然后呼叫notifyDataSetChanged()
并呼叫dialog.dismiss()
。
在解除对话框之前,用户不会看到项目的选择。
我通过添加postdelay解决这个问题来解决这个问题,也许这个问题有更好的解决方案吗?
这是我的代码:
public class SettingsPopupAdapter extends BaseAdapter
{
private List<SettingsItem> _data;
private Context _con;
public SettingsPopupAdapter(Context con, List<SettingsItem> data)
{
_con = con;
_data = data;
}
@Override
public int getCount()
{
return _data.size();
}
@Override
public SettingsItem getItem(int position)
{
return _data.get(position);
}
@Override
public long getItemId(int position)
{
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(_con).inflate(R.layout.settings_popup_checkbox_row_item, parent, false);
holder._text = (TextView) convertView.findViewById(R.id.option_text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
SettingsItem item = getItem(position);
holder._text.setText(item.getItemLabel());
holder._text.setSelected(item.isSelected());
return convertView;
}
private static class ViewHolder
{
public TextView _text;
}
public String getSelectedItem()
{
String selectedItem = null;
for (SettingsItem item : _data)
{
if (item.isSelected())
{
selectedItem = item.getItemLabel();
break;
}
}
return selectedItem;
}
public List<String> getSelectedItems()
{
List<String> selectedOptions = new ArrayList<String>();
for (SettingsItem item : _data)
{
if (item.isSelected())
{
selectedOptions.add(item.getItemLabel());
}
}
return selectedOptions;
}
public void setData(ArrayList<SettingsItem> items)
{
_data = items;
notifyDataSetChanged();
}
}
此代码位于我打开对话框的片段中:
private SettingsPopupAdapte _modAdapter;
private ArrayList<SettingsItem> _items;
_modAdapter = new SettingsPopupAdapter(getActivity(),_items);
_modificationListView.setAdapter(_modAdapter);
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = _items.get(position).getItemLabel();
selectExclusiveList(selectedItem);
Bundle b = new Bundle();
b.putInt(Consts.MODIFICATION_TYPE_KEY, _type);
b.putString(Consts.RESPONSE_DATA_KEY,selectedItem);
_listener.onRetrieveData(b);
//show the change before the dialog dismissed
getView().postDelayed(new Runnable()
{
@Override
public void run()
{
dismiss();
}
},200);
}
private void selectExclusiveList(String selectedItem)
{
for (SettingsItem item : _items)
{
item.setSelected(false);
if (item.getItemLabel().equals(selectedItem))
{
item.setSelected(true);
}
}
_modAdapter.setData(_items);
}