Step1: specifying parentActivityName attibute in an activity
Declare which activity is the appropriate parent for each activity. You can do it by specifying parentActivityName attibute in an activity.
<activity android:name="com.example.test.MainActivity2" android:label="@string/title_activity_main_activity2" android:parentActivityName="com.example.test.MainActivity" > </activity>
Step2: Call setDisplayHomeAsUpEnabled() method of getActionBar() in the onCreate()
Call setDisplayHomeAsUpEnabled() method of getActionBar() in the onCreate method of the activity to enable the back button in the top action bar
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity2); getActionBar().setDisplayHomeAsUpEnabled(true); }
Step3: Override onOptionsItemSelected()
When the user presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home.
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } }
Step4: Handling device back button
Overrid onBackPressed() and then calling moveTaskToBack() and finish() method.
@Override public void onBackPressed() { moveTaskToBack(true); MainActivity2.this.finish(); }
Complete Code:
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.test.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.test.MainActivity2" android:label="@string/title_activity_main_activity2" android:parentActivityName="com.example.test.MainActivity" > </activity> </application>
public class MainActivity2 extends Activity { @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity2); getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_activity2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { moveTaskToBack(true); MainActivity2.this.finish(); } }
Next Article: Android - Sending data from one activity to another
For any questions, suggestions and feedback, Please write to us. Thanks for Reading :)
No comments:
Post a Comment