【发布时间】:2014-10-22 17:38:40
【问题描述】:
我正在开发一个 Android 应用程序,并尝试在操作栏按钮和默认的 android 后退按钮上实现向上导航。我需要让它返回到上一个活动,但它只是关闭应用程序。
我在这里阅读了设计指南http://developer.android.com/design/patterns/navigation.html 以及这里的实现内容http://developer.android.com/training/implementing-navigation/ancestral.html,但我仍然遇到问题。
这是我的代码:
我的 MapActivity 调用了一个对话框片段:
public void showProfileDialog() {
// Create an instance of the dialog fragment and show it
ProfileDialogFragment profileDialog = new ProfileDialogFragment();
profileDialog.show(getSupportFragmentManager(), "ProfileDialogFragment");
}
这里是:
public class ProfileDialogFragment extends DialogFragment {
protected FragmentActivity context;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater.inflate(R.layout.dialog_profile, null));
builder.setMessage(R.string.profileName)
.setPositiveButton(R.string.profileButtonTextEdit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//go to profile page
context = getActivity();
Intent i = new Intent(context,ProfilePageActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//i.putExtra("key", "value"); //Optional parameters
context.startActivity(i);
context.finish();
}
})
.setNegativeButton(R.string.profileButtonTextClose, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//effectivly a cancel button
ProfileDialogFragment.this.getDialog().cancel();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
这会调用个人资料页面:
public class ProfilePageActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_screen);
getActionBar().setDisplayHomeAsUpEnabled(true); // make up navigation
final Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return false;
}
}
在清单中,我指定了父活动:
<activity
android:name="com.wc.test.ProfilePageActivity"
android:label="@string/app_name"
android:parentActivityName="com.wc.test.MyMapActivity">
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.wc.test.MyMapActivity" />
</activity>
这表明个人资料页面应该返回到主要活动,而是关闭应用程序。
我猜这可能是因为我要“通过”片段对话框,但不知道如何修复它。
【问题讨论】:
标签: java android eclipse android-activity android-fragments