前段时间弄了2个Gallery跟ImageSwitcher实现了图片浏览。
今天介绍一种在对话框上实现图像选择。
先声明,是借鉴别人的做法,觉得确实很好。
实现的效果如下:
部分关键代码如下:
对话框的设置:
重点是
setView(imageChooseView)
这个属性
public void initImageChooseDialog() { if(imageChooseDialog == null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("请选择图像") .setView(imageChooseView).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { imageChanged = true; previousImagePosition = currentImagePosition; imageButton.setImageResource(images[currentImagePosition%images.length]); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { currentImagePosition = previousImagePosition; } }); imageChooseDialog = builder.create(); } }
加载图片的方法:
public void loadImage() { if(imageChooseView == null) { LayoutInflater li = LayoutInflater.from(AddNew.this); imageChooseView = li.inflate(R.layout.imageswitch, null); //通过渲染xml文件,得到一个视图(View),再拿到这个View里面的Gallery gallery = (Gallery)imageChooseView.findViewById(R.id.gallery); //为Gallery装载图片 gallery.setAdapter(new ImageAdapter(this)); gallery.setSelection(images.length/2); is = (ImageSwitcher)imageChooseView.findViewById(R.id.imageswitch); is.setFactory(this); is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); //卸载图片的动画效果 is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); gallery.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { //当前的头像位置为选中的位置 currentImagePosition = arg2; //为ImageSwitcher设置图像 is.setImageResource(images[arg2 % images.length]); } @Override public void onNothingSelected(AdapterView<?> arg0) { }}); } }
重点,adapter的写法:
class ImageAdapter extends BaseAdapter { private Context context; public ImageAdapter(Context context) { this.context = context; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } /** * gallery从这个方法中拿到image */ @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView iv = new ImageView(context); iv.setImageResource(images[position%images.length]); iv.setAdjustViewBounds(true); iv.setLayoutParams(new Gallery.LayoutParams(80,80)); iv.setPadding(15, 10, 15, 10); return iv; } }
//这个是重写的的方法,我给加上注释。我是百度了很久也没找到这个方法的解释。只要对着有道看的源码~~ TAT @Override public View makeView() { ImageView view = new ImageView(this); view.setBackgroundColor(0xff000000);//设置背景边框颜色? view.setScaleType(ScaleType.FIT_CENTER);//设置 显示的类型 居中显示 view.setLayoutParams(new ImageSwitcher.LayoutParams(90,90));//设置显示的图片大小 return view; }