在使用AlertDialog實現單選和多選對話框時,分別設置setSingleChoiceItems()和setMultiChoiceItems()函數。
下面看主要的代碼:
數據源數組:
<resources><!--單選--><string-array name="arr_weather"> <item >晴</item> <item >多云</item> <item >小雨</item> <item >中雨</item> </string-array><!--多選--><string-array name="arr_grasslandGreatType"> <item >羊草</item> <item >牛草</item> </string-array></resources>
Activity中的主要代碼:
點擊事件:
case R.id.edt_sampleWeather:// 天氣選取String[] arrWeather = getResources().getStringArray(R.array.arr_weather);showAlertDialog(arrWeather, selectWeatherId, 0, tv_sampleWeather);break;case R.id.edt_grasslandGreatType:// 草地優勢種選擇showMultiDialog();break;
對應方法:
(1)showAlertDialog()方法,實現單選效果,selectWeatherId 設置選定的條目位置
private void showAlertDialog(final String[] items, int selectId, final int type, final TextView tView) {AlertDialog.Builder builder = new AlertDialog.Builder(CreatePointActivity.this);builder.setSingleChoiceItems(items, selectId, new DialogInterface.OnClickListener() {// 第二個參數是設置默認選中哪一項-1代表默認都不選@Overridepublic void onClick(DialogInterface dialog, int which) {tView.setText(items[which]);if (type == 0) {selectWeatherId = which;} else if (type == 1) {selectGrassLandTypeId = which;} else if (type == 2) {selectAgroTypeId = which;}dialog.dismiss();}});AlertDialog dialog = builder.create();dialog.show();dialog.setCanceledOnTouchOutside(true);// dialog彈出后,點擊界面其他部分dialog消失}(2)showMultiDialog()方法,實現多選效果
boolean[] selected = new boolean[] { false, false };//默認選中位置private void showMultiDialog() {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("草地優勢種選擇列表");DialogInterface.OnMultiChoiceClickListener mutiListener = new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {selected[which] = isChecked;}};builder.setMultiChoiceItems(R.array.arr_grasslandGreatType, selected, mutiListener);DialogInterface.OnClickListener btnListener = new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int which) {String selectedStr = "";for (int i = 0; i < selected.length; i++) {if (selected[i] == true) {selectedStr = selectedStr + " "+ getResources().getStringArray(R.array.arr_grasslandGreatType)[i];}}if (!TextUtils.isEmpty(selectedStr)) {tv_grasslandGreatType.setText(selectedStr);} else {tv_grasslandGreatType.setText("暫無選擇");}}};builder.setNegativeButton("取消", null);builder.setPositiveButton("確定", btnListener);AlertDialog dialog = builder.create();dialog.show();dialog.setCanceledOnTouchOutside(true);// dialog彈出后,點擊界面其他部分dialog消失}以上就是實現的主要方法。
效果如下:
單選:

多選:

本站還給大家提供了有關android開發方面的專題欄目,大家可以參考下:
以上所述是小編給大家介紹的Android使用AlertDialog實現的信息列表單選、多選對話框功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答