Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 7.83 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Fragment does not work
  2. public class MainActivity extends FragmentActivity {
  3. /** Called when the activity is first created. */
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) {
  6.     super.onCreate(savedInstanceState);
  7.     setContentView(R.layout.activity_main);
  8.  
  9.     if (savedInstanceState == null) {
  10.         getSupportFragmentManager().beginTransaction()
  11.                 .replace(R.id.fragment_placeholder, new MyFragment())
  12.                 .commit();
  13.     }
  14.        
  15. public class MyFragment extends ListFragment implements
  16.     LoaderCallbacks<Void> {
  17.  
  18. public static final String TAG = "Test_Tuo";
  19.  
  20. private MyAdapter mAdapter;
  21. private ArrayList<String> mItems;
  22. private LayoutInflater mInflater;
  23. private Button mBtnReload;
  24.  
  25. private boolean mFirstRun = true;
  26. private final Handler mHandler = new Handler();
  27.  
  28. private static final String[] WORDS = { "Lorem", "ipsum", "dolor", "sit",
  29.         "amet", "consectetur", "adipiscing", "elit", "Fusce", "pharetra",
  30.         "luctus", "sodales" };
  31.  
  32. private static final int SIZE = 12;
  33. private static final int SLEEP = 2000;
  34.  
  35. private final int wordBarColor = R.color.word_bar;
  36. private Resources mRes;
  37.  
  38. @Override
  39. public void onActivityCreated(Bundle savedInstanceState) {
  40.     super.onActivityCreated(savedInstanceState);
  41.     // this is really important in order to save the state across screen
  42.     // configuration changes for example
  43.     setRetainInstance(true);
  44.  
  45.     // LoaderManager.enableDebugLogging(true);
  46.  
  47.     mRes = getResources();
  48.     mInflater = LayoutInflater.from(getActivity());
  49.  
  50.     mBtnReload = (Button) getActivity().findViewById(R.id.btn);
  51.     mBtnReload.setOnClickListener(new View.OnClickListener() {
  52.  
  53.         @Override
  54.         public void onClick(View v) {
  55.             // first time
  56.             if (mFirstRun) {
  57.                 Log.d(TAG, "Parte mFirstRun");
  58.                 mFirstRun = false;
  59.                 mBtnReload.setText(mRes.getString(R.string.restart));
  60.  
  61.                 startLoading();
  62.             }
  63.             // already started once
  64.             else {
  65.                 Log.d(TAG, "Parte restart");
  66.                 restartLoading();
  67.             }
  68.         }
  69.     });
  70.  
  71.     // you only need to instantiate these the first time your fragment is
  72.     // created; then, the method above will do the rest
  73.     if (mAdapter == null) {
  74.         mItems = new ArrayList<String>();
  75.         mAdapter = new MyAdapter(getActivity(), mItems);
  76.     }
  77.     getListView().setAdapter(mAdapter);
  78.  
  79.     // ---- magic lines starting here -----
  80.     // call this to re-connect with an existing
  81.     // loader (after screen configuration changes for e.g!)
  82.     LoaderManager lm = getLoaderManager();
  83.     if (lm.getLoader(0) != null) {
  84.         lm.initLoader(0, null, this);
  85.     }
  86.     // ----- end magic lines -----
  87.  
  88.     if (!mFirstRun) {
  89.         mBtnReload.setText(mRes.getString(R.string.restart));
  90.     }
  91. }
  92.  
  93. protected void startLoading() {
  94.     showDialog();
  95.  
  96.     // first time we call this loader, so we need to create a new one
  97.     getLoaderManager().initLoader(0, null, this);
  98. }
  99.  
  100. protected void restartLoading() {
  101.     showDialog();
  102.  
  103.     mItems.clear();
  104.     mAdapter.notifyDataSetChanged();
  105.     getListView().invalidateViews();
  106.  
  107.     // --------- the other magic lines ----------
  108.     // call restart because we want the background work to be executed
  109.     // again
  110.     Log.d(TAG, "restartLoading(): re-starting loader");
  111.     getLoaderManager().restartLoader(0, null, this);
  112.     // --------- end the other magic lines --------
  113. }
  114.  
  115. @Override
  116. public Loader<Void> onCreateLoader(int id, Bundle args) {
  117.     AsyncTaskLoader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) {
  118.  
  119.         @Override
  120.         public Void loadInBackground() {
  121.             try {
  122.                 // simulate some time consuming operation going on in the
  123.                 // background
  124.                 Log.d(TAG, "Parte il caricamento dei dati");
  125.  
  126.                 for (int i = 0; i < SIZE; ++i) {
  127.                     mItems.add(WORDS[i]);
  128.                 }
  129.  
  130.                 Thread.sleep(SLEEP);
  131.             } catch (InterruptedException e) {
  132.                 Log.d(TAG, "eccezione"+e.toString());
  133.             }
  134.             return null;
  135.         }
  136.     };
  137.     // somehow the AsyncTaskLoader doesn't want to start its job without
  138.     // calling this method
  139.     loader.forceLoad();
  140.     return loader;
  141. }
  142.  
  143. @Override
  144. public void onLoadFinished(Loader<Void> loader, Void result) {
  145.  
  146.     mAdapter.notifyDataSetChanged();
  147.     hideDialog();
  148.     Log.d(TAG, "onLoadFinished(): done loading!");
  149.  
  150. }
  151.  
  152. @Override
  153. public void onLoaderReset(Loader<Void> loader) {
  154. }
  155.  
  156. private class MyAdapter extends ArrayAdapter<String> {
  157.  
  158.     public MyAdapter(Context context, List<String> objects) {
  159.         super(context, R.layout.item_list, R.id.text, objects);
  160.     }
  161.  
  162.     @Override
  163.     public View getView(int position, View convertView, ViewGroup parent) {
  164.         View view = convertView;
  165.         Wrapper wrapper;
  166.  
  167.         if (view == null) {
  168.             view = mInflater.inflate(R.layout.item_list, null);
  169.             wrapper = new Wrapper(view);
  170.             view.setTag(wrapper);
  171.         } else {
  172.             wrapper = (Wrapper) view.getTag();
  173.         }
  174.  
  175.         wrapper.getTextView().setText(getItem(position));
  176.         wrapper.getBar().setBackgroundColor(
  177.                 getResources().getColor(wordBarColor));
  178.         return view;
  179.     }
  180.  
  181. }
  182.  
  183. // use an wrapper (or view holder) object to limit calling the
  184. // findViewById() method, which parses the entire structure of your
  185. // XML in search for the ID of your view
  186. private static class Wrapper {
  187.     private final View mRoot;
  188.     private TextView mText;
  189.     private View mBar;
  190.  
  191.     public Wrapper(View root) {
  192.         mRoot = root;
  193.     }
  194.  
  195.     public TextView getTextView() {
  196.         if (mText == null) {
  197.             mText = (TextView) mRoot.findViewById(R.id.text);
  198.         }
  199.         return mText;
  200.     }
  201.  
  202.     public View getBar() {
  203.         if (mBar == null) {
  204.             mBar = mRoot.findViewById(R.id.bar);
  205.         }
  206.         return mBar;
  207.     }
  208. }
  209.  
  210. public static class MyAlertDialog extends DialogFragment {
  211.     /*
  212.      * All subclasses of Fragment must include a public empty constructor.
  213.      * The framework will often re-instantiate a fragment class when needed,
  214.      * in particular during state restore, and needs to be able to find this
  215.      * constructor to instantiate it. If the empty constructor is not
  216.      * available, a runtime exception will occur in some cases during state
  217.      * restore.
  218.      */
  219.     public MyAlertDialog() {
  220.     }
  221.  
  222.     @Override
  223.     public Dialog onCreateDialog(Bundle savedInstanceState) {
  224.         ProgressDialog progress = new ProgressDialog(getActivity());
  225.         progress.setMessage(getString(R.string.loading));
  226.         return progress;
  227.     }
  228. }
  229.  
  230. private void showDialog() {
  231.     FragmentTransaction ft = getFragmentManager().beginTransaction();
  232.     Fragment prev = getFragmentManager().findFragmentByTag("dialog");
  233.     if (prev != null) {
  234.         ft.remove(prev);
  235.     }
  236.  
  237.     // Create and show the dialog.
  238.     DialogFragment newFragment = new MyAlertDialog();
  239.     newFragment.show(ft, "dialog");
  240. }
  241.  
  242. private void hideDialog() {
  243.     mHandler.post(new Runnable() {
  244.  
  245.         @Override
  246.         public void run() {
  247.             FragmentTransaction ft = getFragmentManager()
  248.                     .beginTransaction();
  249.             Fragment prev = getFragmentManager()
  250.                     .findFragmentByTag("dialog");
  251.             if (prev != null) {
  252.                 ft.remove(prev).commit();
  253.             }
  254.         }
  255.     });
  256. }
  257.        
  258. <?xml version="1.0" encoding="utf-8"?>
  259.  <LinearLayout
  260. xmlns:android="http://schemas.android.com/apk/res/android"
  261. android:orientation="vertical"
  262. android:layout_width="fill_parent"
  263. android:layout_height="fill_parent">
  264. <FrameLayout
  265.     android:id="@+id/fragment_placeholder"
  266.     android:layout_width="fill_parent"
  267.     android:layout_height="0dp"
  268.     android:layout_weight="1" />
  269. <Button
  270.     android:id="@+id/btn"
  271.     android:layout_width="wrap_content"
  272.     android:layout_height="wrap_content"
  273.     android:text="@string/start"/>