要实现Android对话框改变Activity的变量,可以使用接口回调的方式。以下是一个示例代码:
在Activity中定义一个接口,用于在对话框中更改变量的回调:
public interface DialogCallback {
void onVariableChanged(String newValue);
}
在Activity中实现该接口:
public class MainActivity extends AppCompatActivity implements DialogCallback {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
}
private void showDialog() {
MyDialogFragment dialog = new MyDialogFragment();
dialog.setCallback(this);
dialog.show(getSupportFragmentManager(), "dialog");
}
@Override
public void onVariableChanged(String newValue) {
textView.setText(newValue);
}
}
创建一个自定义的对话框Fragment:
public class MyDialogFragment extends DialogFragment {
private DialogCallback callback;
public void setCallback(DialogCallback callback) {
this.callback = callback;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Change Variable")
.setMessage("Enter new value:")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = getDialog().findViewById(R.id.edit_text);
String newValue = editText.getText().toString();
callback.onVariableChanged(newValue);
}
})
.setNegativeButton("Cancel", null);
return builder.create();
}
}
在对话框的点击事件中,通过回调将新值传递给Activity,并在回调方法中更新变量的值。