-1

How can i start a Fragment in the AboutAndHelpActivity instead of the Activity itself or how can i put the Fragment in startActivity()?

//if it is the first start of the app, open HelpFragment once.

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getBoolean("isFirstRun", true);
    if (isFirstRun) {

        startActivity(new Intent(MainActivity.this, AboutAndHelpActivity.class));
        Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
                .show();
    }
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
            .putBoolean("isFirstRun", false).commit();
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
SGE59
  • 37
  • 5

3 Answers3

1

Before you want to think about activity and fragment I will suggest you to read about it So that you will get idea Please check the link for fragment information

https://developer.android.com/guide/components/fragments.html

You can add, remove or replace the fragment in the activity You should manage fragment life cycle. Otherwise you might get some unexpected UI or app issues

Shaahul
  • 538
  • 4
  • 11
0

You are completely misunderstand what is Activities and Fragments. Read about them again.

tl;dr: Activity - base unit. Fragment - part. Fragment can be only hosted in some activity, and can't be displayed other way.

Here how you can display fragment in activity:

getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_holder,new MyFragment())
            .addToBackStack(MyFragment.class.getSimpleName())
            .commit();
Ekalips
  • 1,473
  • 11
  • 20
  • I know the difference. But i want to start a fragment once the first time the app is started. Not only the activity. How can I do that.. – SGE59 Jan 23 '17 at 16:01
  • You have two options: 1) Add fragment to current activity (some startup activity). 2) When you'll start your main activity, add some extra to tell activity to show fragment. –  Ekalips Jan 23 '17 at 16:03
  • You can put `Extra` something in `Intent`. Put Boolean "isFirstRun" and in activity do `getIntent()` and `getExtras()` –  Ekalips Jan 23 '17 at 16:04
0

If I understood you correctly, AboutAndHelpActivity is supposed to be started on the app's first run and house a Fragment. If so, the starting the Activity part is already solved in you initial question, so what remains is showing the Fragment. Two options make sense to me:

  1. In case AboutAndHelpActivity's only job is to house the Fragment and won't be started for any other purpose, the Fragment can be added to its layout xml.

  2. Otherwise, the Fragment needs to be added dynamically based on an Intent extra as already pointed out by @Ekalips.

Micha
  • 396
  • 2
  • 8