- Fragment does not work
- public class MainActivity extends FragmentActivity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- if (savedInstanceState == null) {
- getSupportFragmentManager().beginTransaction()
- .replace(R.id.fragment_placeholder, new MyFragment())
- .commit();
- }
- public class MyFragment extends ListFragment implements
- LoaderCallbacks<Void> {
- public static final String TAG = "Test_Tuo";
- private MyAdapter mAdapter;
- private ArrayList<String> mItems;
- private LayoutInflater mInflater;
- private Button mBtnReload;
- private boolean mFirstRun = true;
- private final Handler mHandler = new Handler();
- private static final String[] WORDS = { "Lorem", "ipsum", "dolor", "sit",
- "amet", "consectetur", "adipiscing", "elit", "Fusce", "pharetra",
- "luctus", "sodales" };
- private static final int SIZE = 12;
- private static final int SLEEP = 2000;
- private final int wordBarColor = R.color.word_bar;
- private Resources mRes;
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- // this is really important in order to save the state across screen
- // configuration changes for example
- setRetainInstance(true);
- // LoaderManager.enableDebugLogging(true);
- mRes = getResources();
- mInflater = LayoutInflater.from(getActivity());
- mBtnReload = (Button) getActivity().findViewById(R.id.btn);
- mBtnReload.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // first time
- if (mFirstRun) {
- Log.d(TAG, "Parte mFirstRun");
- mFirstRun = false;
- mBtnReload.setText(mRes.getString(R.string.restart));
- startLoading();
- }
- // already started once
- else {
- Log.d(TAG, "Parte restart");
- restartLoading();
- }
- }
- });
- // you only need to instantiate these the first time your fragment is
- // created; then, the method above will do the rest
- if (mAdapter == null) {
- mItems = new ArrayList<String>();
- mAdapter = new MyAdapter(getActivity(), mItems);
- }
- getListView().setAdapter(mAdapter);
- // ---- magic lines starting here -----
- // call this to re-connect with an existing
- // loader (after screen configuration changes for e.g!)
- LoaderManager lm = getLoaderManager();
- if (lm.getLoader(0) != null) {
- lm.initLoader(0, null, this);
- }
- // ----- end magic lines -----
- if (!mFirstRun) {
- mBtnReload.setText(mRes.getString(R.string.restart));
- }
- }
- protected void startLoading() {
- showDialog();
- // first time we call this loader, so we need to create a new one
- getLoaderManager().initLoader(0, null, this);
- }
- protected void restartLoading() {
- showDialog();
- mItems.clear();
- mAdapter.notifyDataSetChanged();
- getListView().invalidateViews();
- // --------- the other magic lines ----------
- // call restart because we want the background work to be executed
- // again
- Log.d(TAG, "restartLoading(): re-starting loader");
- getLoaderManager().restartLoader(0, null, this);
- // --------- end the other magic lines --------
- }
- @Override
- public Loader<Void> onCreateLoader(int id, Bundle args) {
- AsyncTaskLoader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) {
- @Override
- public Void loadInBackground() {
- try {
- // simulate some time consuming operation going on in the
- // background
- Log.d(TAG, "Parte il caricamento dei dati");
- for (int i = 0; i < SIZE; ++i) {
- mItems.add(WORDS[i]);
- }
- Thread.sleep(SLEEP);
- } catch (InterruptedException e) {
- Log.d(TAG, "eccezione"+e.toString());
- }
- return null;
- }
- };
- // somehow the AsyncTaskLoader doesn't want to start its job without
- // calling this method
- loader.forceLoad();
- return loader;
- }
- @Override
- public void onLoadFinished(Loader<Void> loader, Void result) {
- mAdapter.notifyDataSetChanged();
- hideDialog();
- Log.d(TAG, "onLoadFinished(): done loading!");
- }
- @Override
- public void onLoaderReset(Loader<Void> loader) {
- }
- private class MyAdapter extends ArrayAdapter<String> {
- public MyAdapter(Context context, List<String> objects) {
- super(context, R.layout.item_list, R.id.text, objects);
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- View view = convertView;
- Wrapper wrapper;
- if (view == null) {
- view = mInflater.inflate(R.layout.item_list, null);
- wrapper = new Wrapper(view);
- view.setTag(wrapper);
- } else {
- wrapper = (Wrapper) view.getTag();
- }
- wrapper.getTextView().setText(getItem(position));
- wrapper.getBar().setBackgroundColor(
- getResources().getColor(wordBarColor));
- return view;
- }
- }
- // use an wrapper (or view holder) object to limit calling the
- // findViewById() method, which parses the entire structure of your
- // XML in search for the ID of your view
- private static class Wrapper {
- private final View mRoot;
- private TextView mText;
- private View mBar;
- public Wrapper(View root) {
- mRoot = root;
- }
- public TextView getTextView() {
- if (mText == null) {
- mText = (TextView) mRoot.findViewById(R.id.text);
- }
- return mText;
- }
- public View getBar() {
- if (mBar == null) {
- mBar = mRoot.findViewById(R.id.bar);
- }
- return mBar;
- }
- }
- public static class MyAlertDialog extends DialogFragment {
- /*
- * All subclasses of Fragment must include a public empty constructor.
- * The framework will often re-instantiate a fragment class when needed,
- * in particular during state restore, and needs to be able to find this
- * constructor to instantiate it. If the empty constructor is not
- * available, a runtime exception will occur in some cases during state
- * restore.
- */
- public MyAlertDialog() {
- }
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- ProgressDialog progress = new ProgressDialog(getActivity());
- progress.setMessage(getString(R.string.loading));
- return progress;
- }
- }
- private void showDialog() {
- FragmentTransaction ft = getFragmentManager().beginTransaction();
- Fragment prev = getFragmentManager().findFragmentByTag("dialog");
- if (prev != null) {
- ft.remove(prev);
- }
- // Create and show the dialog.
- DialogFragment newFragment = new MyAlertDialog();
- newFragment.show(ft, "dialog");
- }
- private void hideDialog() {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- FragmentTransaction ft = getFragmentManager()
- .beginTransaction();
- Fragment prev = getFragmentManager()
- .findFragmentByTag("dialog");
- if (prev != null) {
- ft.remove(prev).commit();
- }
- }
- });
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <FrameLayout
- android:id="@+id/fragment_placeholder"
- android:layout_width="fill_parent"
- android:layout_height="0dp"
- android:layout_weight="1" />
- <Button
- android:id="@+id/btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/start"/>