Android中Dialog中添加ListView

1.自定义item的布局文件




    


    

2.自定义adapter

/**
 *  ListAdapter
 */
public class DialogItemAdapter extends BaseAdapter {
    //这里可以传递个对象,用来控制不同的item的效果
    //比如每个item的背景资源,选中样式等
    public List list;
    LayoutInflater inflater;

    public DialogItemAdapter(Context context, List list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public String getItem(int i) {
        if (i == getCount() || list == null) {
            return null;
        }
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.dialog_item, null);
            holder.typeTextview = (TextView) convertView.findViewById(R.id.textview);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textview.setText(getItem(position));
        return convertView;
    }

    public static class ViewHolder {
        public TextView textview;
    }
}

3.添加数据并使用

DialogItemAdapter adapter = new DialogItemAdapter(mActivity ,iniDatas());

AlertDialog alertDialog = new AlertDialog
                .Builder(mActivity)
                .setSingleChoiceItems(adapter, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //ToastUtil.showToastShort("信息:");
                        dialog.dismiss();
                    }
                }).create();

        alertDialog.show();
     

4.设置dialog的宽高

以下代码,需要在show()方法之后。

//将对话框的大小按屏幕大小的百分比设置
Window window = alertDialog.getWindow() ;
WindowManager m = getActivity().getWindowManager();
Display d = m.getDefaultDisplay();                      // 获取屏幕宽、高用
WindowManager.LayoutParams p = window.getAttributes();  // 获取对话框当前的参数值
p.height = (int) (d.getHeight() * 0.6);                 // 改变的是dialog框在屏幕中的位置而不是大小
p.width = (int) (d.getWidth() * 0.65);                  // 宽度设置为屏幕的0.65
window.setAttributes(p);

 

你可能感兴趣的:(Android之从头自学)