Android alertDialog

9 篇文章 ¥79.90 ¥99.00
这个示例展示了如何在Android应用中创建一个AlertDialog,让用户从预设的水果列表中进行多选,并在用户点击确认时显示所选的水果。通过DialogInterface.OnMultiChoiceClickListener处理用户的选择,并使用Toast展示结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.dialogue;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;


public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final String[] arrayFruit = new String[] { "苹果", "橘子", "草莓", "香蕉" };
final boolean[] arrayFruitSelected = new boolean[] { true, true, false,
false };


Dialog alertDialog = new AlertDialog.Builder(this)
.setTitle("你喜欢吃哪种水果?")
.setIcon(R.drawable.ic_launcher)
.setMultiChoiceItems(arrayFruit, arrayFruitSelected,
new DialogInterface.OnMultiChoiceClickListener() {


@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
arrayFruitSelected[which] = isChecked;
}
})
.setPositiveButton("确认", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayFruitSelected.length; i++) {
if (arrayFruitSelected[i] == true) {
stringBuilder.append(arrayFruit[i] + "、");
}
}
Toast.makeText(MainActivity.this,
stringBuilder.toString(), Toast.LENGTH_SHORT)
.show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).create();
alertDialog.show();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值