目前,当用户打开我的应用程序时,会打开一个 AlertDialog
,询问他们是否要升级到专业版。
我需要在 AlertDialog
中添加一个 CheckBox
,这将使应用在用户打开应用时不再显示 AlertDialog
。
这是我现在的 AlertDialog
的内容:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" MY_TEXT");
builder.setMessage(" MY_TEXT ")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Uri uri = Uri.parse("market://details?id=MY_APP_PACKAGE");
Intent intent = new Intent (Intent.ACTION_VIEW, uri);
startActivity(intent); }
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
如何将 CheckBox
添加到 AlertDialog
以使应用在用户打开应用时不再显示 AlertDialog
?
最佳答案
您必须在 AlertDialog.Builder
对象上使用方法 setView(View)
。这会将传入的 View
放在消息区域和按钮之间。只需用 CheckBox
为 View
充气并将其传入。这是一个示例:
checkbox.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="@+id/checkbox"
style="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
</FrameLayout>
Activity 中的代码
View checkBoxView = View.inflate(this, R.layout.checkbox, null);
CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Save to shared preferences
}
});
checkBox.setText("Text to the right of the check box.");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" MY_TEXT");
builder.setMessage(" MY_TEXT ")
.setView(checkBoxView)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Uri uri = Uri.parse("market://details?id=MY_APP_PACKAGE");
Intent intent = new Intent (Intent.ACTION_VIEW, uri);
startActivity(intent); }
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
关于android - 如何将复选框添加到警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763643/