【发布时间】:2020-06-25 16:00:44
【问题描述】:
我有一个对话框片段,带有一个“不再显示”复选框,我想使用它,但由于某种原因它不起作用,无论我在检查中标记什么,对话框都会继续显示盒子。
这是我的 DialogFragment 类:
public class DialogConnectFragment extends DialogFragment {
private CheckBox checkBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Connect Smart Device?")
.setPositiveButton("Yes, Connect!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FragmentManager fragManager = getActivity().getSupportFragmentManager();
fragManager.beginTransaction()
.replace(R.id.frameLayout_remote_activity, new CustomizedDeviceListFragment())
.addToBackStack(null)
.commit();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
dialog.cancel();
}
});
builder.setView(R.layout.fragment_dialog_connect);
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_connect, null);
checkBox = (CheckBox) view.findViewById(R.id.checkBox);
SharedPreferences sharedPref = getActivity().getSharedPreferences(Utils.settingsTAG, 0);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Store the isChecked to Preference here
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(DONT_SHOW_DIALOG_MSG, isChecked);
editor.apply();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
这是我的片段布局:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dialog_connect_smart_device_content"
android:layout_gravity="start"
android:id="@+id/connectDialogMessage"
android:textSize="15sp"
android:layout_marginBottom="5dp"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dialog_checkbox_connect_smart_device"
android:layout_gravity="start"
android:id="@+id/checkBox"
/>
这是我决定是否显示片段的方式:
SharedPreferences sharedPref = getActivity().getSharedPreferences(Utils.settingsTAG, 0);
boolean dontShowDialog = sharedPref.getBoolean(DONT_SHOW_DIALOG_MSG, false);
if (!dontShowDialog) {
FragmentManager fragManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
DialogConnectFragment dialogConnectSmartDeviceFragment = new DialogConnectFragment ();
dialogConnectSmartDeviceFragment.show(fragManager, "DialogFrag");
}
看起来我已经正确实现了,但是经过多次测试,它什么也没做......
【问题讨论】: