我正在尝试在一个片段中执行操作,然后移动到前一个片段并显示带有消息的快餐栏,确认第一个片段中的操作。然而,我正在创建并显示第一个片段(我正在移动的那个)中的小吃吧,并且小吃栏没有出现在我正在改变的片段中,可能是因为它显示在片段中我正在移动从
我在alertdialog中执行代码:
builder.setPositiveButton(positiveText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dbHandler.deleteExercise(exercise.getId());
// Making the snackbar here did not work, either.
getFragmentManager().popBackStack();
Snackbar snack = Snackbar.make(mainLayout, "Exercise deleted", Snackbar.LENGTH_SHORT);
snack.show();
}
});
知道如何实现这个目标吗?
谢谢!
修改
答案 0 :(得分:0)
我最终通过主Fragments
在Activity
之间实现了消息传递,并检查了片段onResume()
方法中的消息:
<强> MainActivity:强>
private String fragmentTransactionMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Snip
// Initialize fragment transaction message
fragmentTransactionMessage = null;
// Snip
}
// Three methods used to send information (text) between fragments
public void setFragmentTransactionMessage(String message) {
this.fragmentTransactionMessage = message;
}
public String getFragmentTransactionMessage() {
return fragmentTransactionMessage;
}
public void resetFragmentTransactionMessage() {
this.fragmentTransactionMessage = null;
}
片段2:
// Remove exercise from database
dbHandler.deleteExercise(exercise.getId());
// Update message in main activity
((MainActivity)getActivity()).setFragmentTransactionMessage("Item deleted");
// Move to previous fragment
getFragmentManager().popBackStack();
片段1:
@Override
public void onResume() {
super.onResume();
// Check for messages in main activity
String message = ((MainActivity)getActivity()).getFragmentTransactionMessage();
// If any, display as snackbar
if(message != null) {
Snackbar snack = Snackbar.make(mainLayout, message, Snackbar.LENGTH_SHORT);
snack.show();
// Reset message in activity
((MainActivity)getActivity()).resetFragmentTransactionMessage();
}
}
答案 1 :(得分:0)
另一建议是将getFragmentManager().popBackStack();
包装在采用Runnable Obj的方法中,该方法将在选定的延迟后运行
例如:
public void goBack(Runnable runAfterBack, long delay) {
mFragmentActivity.onBackPressed();
if (runAfterBack != null) {
(new Handler(Looper.getMainLooper())).postDelayed(runAfterBack, delay);
}
}
用法:
goBack(new Runnable() {
@Override
public void run() {
Toast.makeText(mActivity, "STRING", Toast.LENGTH_SHORT).show();}
}, 1500);