1 回答
TA贡献1829条经验 获得超13个赞
溶液:要将数据从警报对话框传递到父片段,更简单的方法是让对话框扩展 DialogFragment。然后使用它们和在它们之间发送数据。setTargetFragmentsetTargetFragment
因为你没有发布父片段代码,所以我假设这里是你的父片段的xml和java代码。
主碎屑.java
public class MainFragment extends Fragment implements SchulfachDialogListener{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button btnShowAlertDialog = view.findViewById(R.id.button_show_alert_dialog);
btnShowAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SchulfachDialog dialog = new SchulfachDialog();
dialog.setTargetFragment(MainFragment.this, 0);
dialog.show(requireActivity().getSupportFragmentManager(), null);
}
});
return view;
}
@Override
public void applyTexts(String text) {
Toast.makeText(requireActivity(), text, Toast.LENGTH_SHORT).show();
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Alert Dialog"
android:id="@+id/button_show_alert_dialog"/>
</LinearLayout>
让警报对话框扩展 DialogFragment。
public class SchulfachDialog extends DialogFragment {
private EditText editTextName;
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
View view = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_schulfach, null);
builder.setView(view)
.setTitle("Add new subject")
.setMessage("Message")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = editTextName.getText().toString();
SchulfachDialogListener listener = (SchulfachDialogListener) getTargetFragment();
listener.applyTexts(name);
}
});
editTextName = view.findViewById(R.id.edit_name);
return builder.create();
}
}
添加回答
举报