Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DetachableAdapter extends BaseAdapter {
- private Context mContext;
- private List<String> mData;
- public DetachableAdapter() {
- // no Context yet.
- }
- public void setContext(Context context) {
- mContext = context;
- }
- public void setData(List<String> data) {
- mData = data;
- notifyDataSetChanged();
- }
- @Override
- public int getCount() {
- return mData.size();
- }
- @Override
- public Object getItem(int location) {
- return mData.get(location);
- }
- @Override
- public long getItemId(int location) {
- return location;
- }
- @Override
- public View getView(int location, View convertView, ViewGroup root) {
- // context can't be null here since this code is not exectued w/o context
- LayoutInflater inflater = LayoutInflater.from(mContext);
- View view = convertView;
- if (view == null) {
- view = inflater.inflate(android.R.layout.simple_list_item_1, null);
- }
- ((TextView) view).setText(mData.get(location));
- return view;
- }
- }
- ///////////////////////////////////////////////////////////////
- public class RetainedFragment extends ListFragment {
- // ok to keep since it does not keep the reference to context
- private final DetachableAdapter mAdapter = new DetachableAdapter();
- // ok to keep since it does not keep any references
- private final List<String> mData = new ArrayList<String>();
- public RetainedFragment() {
- for (int i = 0; i < 100; i++) {
- mData.add("SomeData:" + i);
- }
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setRetainInstance(true);
- setListAdapter(mAdapter);
- }
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
- mAdapter.setContext(activity);
- }
- @Override
- public void onDetach() {
- super.onDetach();
- mAdapter.setContext(null);
- }
- @Override
- public void onResume() {
- super.onStart();
- updateList();
- }
- private void updateList() {
- // simulate some sort of updates probably due to listeners..
- Collections.shuffle(mData);
- mAdapter.setData(mData);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement