gpt4 book ai didi

java - 仅针对 3 个 fragment 中的 2 个出现 OnBackPressed() 警报框

转载 作者:行者123 更新时间:2023-12-01 09:49:54 28 4
gpt4 key购买 nike

我正在寻找一种方法来发出“你确定你已经完成了吗?”当用户在编辑注释并添加注释 fragment 时按下后退导航按钮时,会出现警报框,但在查看注释 fragment 时不会出现警报框。下面我附上了每个 fragment 链接到的 Activity 的代码。如果您需要更多来自不同领域的代码,请告诉我。

public class NoteDetailActivity extends AppCompatActivity {


public static final String NEW_NOTE_EXTRA = "New Note";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_detail);
createAndFragment();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);


}


private void createAndFragment(){

Intent intent = getIntent();
MainActivity.FragmentToLaunch fragmentToLaunch = (MainActivity.FragmentToLaunch) intent.getSerializableExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA);

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

switch(fragmentToLaunch){
case EDIT:
NoteEditFragment noteEditFragment = new NoteEditFragment();
setTitle(R.string.edit_fragment_title);
fragmentTransaction.add(R.id.note_container, noteEditFragment, "NOTE_EDIT_FRAGMENT");
break;
case VIEW:
NoteViewFragment noteViewFragment = new NoteViewFragment();
setTitle(R.string.view_fragment_title);
fragmentTransaction.add(R.id.note_container, noteViewFragment, "NOTE_VIEW_FRAGMENT");
break;
case CREATE:
NoteEditFragment noteCreateFragment = new NoteEditFragment();
setTitle(R.string.create_fragment_title);

Bundle bundle = new Bundle();
bundle.putBoolean(NEW_NOTE_EXTRA, true);
noteCreateFragment.setArguments(bundle);

fragmentTransaction.add(R.id.note_container, noteCreateFragment, "NOTE_CREATE_FRAGMENT");
break;

}

fragmentTransaction.commit();

}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NoteDetailActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
}

最佳答案

通过获取 fragment 标签来做到这一点

获取这样的标签

 Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
String tag = fragment.getTag(); // This will return the tag of fragment

然后使用 if-else 来完成任务

  if (tag.equalsIgnoreCase("Home")) {
// Open aLERT box
}else if (tag.equalsIgnoreCase("Home2")) {
// Open aLERT box
}else if (tag.equalsIgnoreCase("Home2")) {
// Open aLERT box
}else{
// dO STUFF HERE
}

不要忘记添加fragment标签

关于java - 仅针对 3 个 fragment 中的 2 个出现 OnBackPressed() 警报框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com