[英]How do I pass a boolean value from a DialogFragment to another Fragment in Android?
I'm trying to make it so a clear button will open up an alert dialog which has a yes or no.我正在尝试这样做,以便清除按钮打开一个警报对话框,其中包含是或否。 When clicking the yes button, it should pass a bool value from the dialog frag to the other frag.
单击是按钮时,它应该将一个布尔值从对话框片段传递给另一个片段。 If the value is true, which it should be when yes is clicked, it will call methods which will clear a database.
如果该值为真(单击“是”时应该为真),它将调用将清除数据库的方法。 Here is the dialog frag and the part of the frag where I'm trying to implement it.
这是对话片段和我试图实现它的片段的一部分。 I can't get the dialog box to appear, but so far it does make the screen darker which I assume means I'm not hooking it up right.
我无法让对话框出现,但到目前为止它确实使屏幕变暗,我认为这意味着我没有正确连接它。
Dialog frag:对话框片段:
public class DialogClear extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.clear_dialog, null);
final Button yes = dialogView.findViewById(R.id.yes);
final Button no = dialogView.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
}
Here is how I'm trying to call it from my frag这是我试图从我的碎片中调用它的方式
clearButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialogClear = new DialogClear();
dialogClear.setTargetFragment(BloodPressureFragment.this, 1);
dialogClear.show(getFragmentManager(),"");
dataManager.clearDatabase();
dataManager.createDatabase();
dataText.setText("");
dataText.setBackgroundResource(R.drawable.no_border);
updateList();
}
});
welcome to code party欢迎来到代码派对
you have many choices to do this job, but i will show you best way for using fragments.你有很多选择来完成这项工作,但我会向你展示使用片段的最佳方式。
As you know, all fragments changes in one activity and extend from it.如您所知,所有片段都在一个活动中发生变化并从中扩展。
So the easy way is this:所以简单的方法是这样的:
1.build public fields in your activity
1.在你的活动中建立公共领域
2.build a getInstant method on activity
2.在activity上构建一个getInstant方法
3.fill and get values of that activity from any fragments that you want show on this
3.填充并从您希望在此显示的任何片段中获取该活动的值
see this example:看这个例子:
public boolean isLocationOn;
this field is build in activity now: in any fragment:该字段现在在活动中构建:在任何片段中:
MainActivity.getInstance().isLocationOn = true;
in other fragment:在其他片段中:
if(MainActivity.getInstance().isLocationOn){
//todo show map or ...
}
in this way you can use anything in fragments这样你就可以在片段中使用任何东西
update me in comments在评论中更新我
You should read and try using 3 thing's to solve this.你应该阅读并尝试使用 3 件事来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.