How to add an Activity to your app and navigate to it using an explicit Intent.
Create an empty Activity through the IDE. IDE will automatically add the essential code to the AndroidManifests.xml file. Make any desirable additions.
<activity android:name="com.example.android.explicitintent.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="com.example.android.explicitintent.ChildActivity" android:label="@string/action_settings" // Name at top of screen for Activity android:parentActivityName=".MainActivity"> // Make sure the back arrow functions properly by declaring parent activity <meta-data // To support Android 4.0 and lower android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity>In new Activity, enable Up navigation.
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Or getActionBar() on older versions before support libraryIn Parent Activity, set up an explicit Intent.
private Button doSomethingCoolButton = (Button) findViewById(R.id.b_do_something_cool); private String text = "Send me!"; // Text to be passed to new Activity mDoSomethingCoolButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Context context = MainActivity.this; /* This is the class that we want to start (and open) when the button is clicked. */ Class destinationActivity = ChildActivity.class; /* * Here, we create the Intent that will start the Activity we specified above in * the destinationActivity variable. The constructor for an Intent also requires a * context, which we stored in the variable named "context". */ Intent startChildActivityIntent = new Intent(context, destinationActivity); startChildActivityIntent.putExtra(Intent.EXTRA_TEXT, text); // Add text as extra data /* * Once the Intent has been created, we can use Activity's method, "startActivity" * to start the ChildActivity. */ startActivity(startChildActivityIntent); } });In new Activity, access and use the extra data.
mDisplayText = (TextView) findViewById(R.id.tv_display); // Find a TextView // Use the getIntent method to store the Intent that started this Activity in a variable Intent intent = getIntent(); // Check if this Intent has the extra text we passed from MainActivity if (intent.hasExtra(Intent.EXTRA_TEXT)) { String enteredText = intent.getStringExtra(Intent.EXTRA_TEXT); mDisplayText.setText(enteredText); // Assign text to TextView }
