Android Dialog和adapter关联,列表形式显示对话框

来源:互联网 发布:网络棋牌平台杀分 编辑:程序博客网 时间:2024/05/16 10:38

上几天忽然想做一个对话框,每次都是觉得很简单,因此就没有注意,后来用到的时候就傻眼了,简单的你不记下来也是没有,因此今天专门记录一下,并附上代码,代码如下:


    private void displayDialog() {        ArrayList<String> arrayList = new ArrayList<String>();        arrayList.add("KKKKKKKKKKK KKK");        arrayList.add("KKKKKKKKKKK");        final Context dialogContext = new ContextThemeWrapper(this,                android.R.style.Theme_Light);        final LayoutInflater dialogInflater = (LayoutInflater) dialogContext                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,                android.R.layout.simple_list_item_1, arrayList) {            @Override            public View getView(int position, View convertView, ViewGroup parent) {                if (convertView == null) {                    convertView = dialogInflater.inflate(                            android.R.layout.simple_list_item_1, parent, false);                }                final TextView text1 = (TextView) convertView                        .findViewById(android.R.id.text1);                final String display = this.getItem(position);                text1.setText(display);                return convertView;            }        };        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(dialogContext,                        "we choose " + adapter.getItem(which),                        Toast.LENGTH_SHORT).show();            }        };        new AlertDialog.Builder(this).setTitle("Display Dialog")                .setSingleChoiceItems(adapter, 0, clickListener).create()                .show();    }

从代码上来看,需要三部分,一部分是adapter,一部分是onClickListener,还有就是AlertDialog,怎么样,觉得是不是很简单,如果不熟悉,简单的操作几下,加深印象,不要等到用到的时候满世界的去找了,代码下载