Issue
Suppose I have two activities - MainActivity
and NameActivity
. MainActivity
opens NameActivity
in order to get some input from the user, by calling startActivityForResult(...)
.
In NameActivity
, I have overridden the finish
method, so that pressing back will return the name as a result:
@Override
public void finish() {
String name = nameEditText.getText().toString();
Intent intent = new Intent();
intent.putExtra(RESULT_NAME, name);
this.setResult(RESULT_OK, intent);
super.finish();
}
In MainActivity, I am handling the result as follows:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_GET_NAME:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra(SelectionActivity.RESULT_NAME);
Toast.makeText(this, "Hi " + name + "!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
Is there a way to get NameActivity
to do the same thing when using the Up button in the action bar?
Note: My app targets Android 4.0 (ICS) and above, so the Up navigation is happening "automagically" - that is, I haven't written any code and have simply specified the parent activity in my Manifest as follows:
<activity
android:name="com.example.subactivitytest.NameActivity"
android:label="@string/title_activity_name"
android:parentActivityName="com.example.subactivitytest.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.subactivitytest.MainActivity" />
</activity>
Thanks!
Solution
You could always just call your finish method in your onOptionsItemSelected()
method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
Also, make sure you've enabled the home button: getActionBar().setHomeButtonEnabled(true);
Answered By - Submersed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.