对于我的SherlockListFragment,我有以下代码,
public class RoutesListFragment extends SherlockListFragment {
private ArrayList<Route> mItems;
private static final String TAG = "ROUTES LIST";
RoutesAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstaceState) {
View view = inflater.inflate(R.layout.fragment_main_lists, container,
false);
// When the setListAdapter is called here,
// it works without any problems
return view;
}
public void updateAdapter() {
// populate the list
mItems = Route.getRouteList();
Log.d(TAG, "Size of mItems : " + mItems.size());
mAdapter = new RoutesAdapter(getActivity(), R.layout.list_item_routes,
mItems);
this.setListAdapter(mAdapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d(TAG, "Clicked item " + position);
}
private class RoutesAdapter extends ArrayAdapter<Route> {
private ArrayList<Route> mItems;
private Context mContext;
int mTextViewResource;
public RoutesAdapter(Context context, int textViewResource,
ArrayList<Route> items) {
super(context, textViewResource);
this.mItems = items;
this.mContext = context;
this.mTextViewResource = textViewResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(mTextViewResource, null);
}
Route route = mItems.get(position);
((TextView) view.findViewById(R.id.route_name)).setText(route
.getRouteName());
((TextView) view.findViewById(R.id.route_number)).setText(Integer
.toString(route.getRouteNumber()));
((TextView) view.findViewById(R.id.direction)).setText(route
.getDirection().toString());
((TextView) view.findViewById(R.id.start_end)).setText(route
.getStartingStop() + " - " + route.getEndingStop());
return view;
}
}
}
我已检查以确保ArrayList<Route> mItems
不为空。
从updateAdapter()
的{{1}}函数调用onPostExecute
函数。
此AsyncTask
用于SherlockListFragment
标签。
它适用于ViewPagerIndicator
onCreateView``函数。
答案 0 :(得分:3)
您只需更改适配器中的数组,然后调用
即可adapter.notifyDataSetChanged();
而不是创建新的适配器
答案 1 :(得分:1)
我必须补充jiduvah的答案。
显然ArrayAdapter
拥有项目ArrayList<Route>
的副本。因此。我必须在致电mAdapter.addAll(Route.getRouteList())
之前致电mAdapter.notifyAll()
。
现在updateAdapter
函数的代码是。
public void updateAdapter() {
mAdapter.addAll(Route.getRouteList());
mAdapter.notifyDataSetChanged();
}
<强>参考强>