[英]Up navigation quitting app in Android development
我正在開發一個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>
這表明配置文件頁面應返回到主要活動,而是關閉應用程序。
我想這可能是因為我要“通過”一個片段對話框,但是不確定如何解決它。
最終,經過多年的代碼挖掘,我發現應用程序退出的原因是由對話框片段中的一行引起的:
context.finish();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.