美文网首页Android 开发收集Android技术知识Android开发
被遗忘的GridLayout展示九宫格(仿照微信上传多张图片)

被遗忘的GridLayout展示九宫格(仿照微信上传多张图片)

作者: Jsonjia | 来源:发表于2018-01-24 11:04 被阅读128次

如果说安卓有四大布局,可能不准确。因为你可能忽略了不常用的2个布局:AbsoluteLayout(绝对布局)GridLayout(网格布局)
GridLayout是在Android4.0中引进的新布局.使用它的理由有两个:
①减少代码量,设置行列,自动换行,适合比较整齐的网格化布局;
②减少嵌套,我们本可以用LinearLayout,RecyclerView或者GridView去实现,从代码量来看,GridLayout是不错的选择,从嵌套布局来看,GridLayout是不错的选择。

这里就介绍GridLayout上传多张图片。目前做的app正好有上传多张图片,因此想记录下来共同学习。

老样子,先上效果图:

效果图.gif

这就是用GridLayout实现的。

步骤

我们对GridLayout进行重写:AddPhotoGridLayout .java

  /**
    * Created by zjp on 2018/1/24 09:11.
    */
    public class AddPhotoGridLayout extends GridLayout {
         public View mDefaultAddImageView;
         private AddPhotoCallback mAddPhotoCallback;
         public int DEFAULT_MAX_PHOTO; //这里可以自定义上传图片张数

         public void setmAddPhotoCallback(AddPhotoCallback mAddPhotoCallback, int imgCounts) {
               this.mAddPhotoCallback = mAddPhotoCallback;
               this.DEFAULT_MAX_PHOTO = imgCounts;
         }
         public AddPhotoGridLayout(Context context) {
               this(context, null);
         }

         public AddPhotoGridLayout(Context context, AttributeSet attrs) {
               this(context, attrs, 0);
         }

         public AddPhotoGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
               super(context, attrs, defStyleAttr);
               mDefaultAddImageView = View.inflate(context, R.layout.item_photo, null);
               ImageView img = (ImageView) mDefaultAddImageView.findViewById(R.id.img);
               img.setImageResource(R.mipmap.add_license); //加号
               addView(mDefaultAddImageView);

               mDefaultAddImageView.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View view) {
                      if (mAddPhotoCallback != null) {
                            mAddPhotoCallback.onClickAddPhoto();
                     }
               }
         });

         public void addPhoto(View photoImage) {
              if (getPhotoCount() == DEFAULT_MAX_PHOTO - 1) {
                  /**
                    * 下面两行代码位置不能换,不然会出现位置错位问题
                    */
                    addView(photoImage, getPhotoCount());
                    removeView(mDefaultAddImageView);
              } else {
                   addView(photoImage, getPhotoCount());
             }
         }

         public int getPhotoCount() {
             return getChildCount() - 1;
         }


         public interface AddPhotoCallback {
              void onClickAddPhoto();
         }

到这里,对GridLayout进行重写已经完成了。

再定义一个照片选择器(如果一个类有很长的代码,会影响代码可读性,所以我喜欢定义工具类,然后在这个类引入它

代码太多,我贴关键代码,稍后我会把代码上传到github上可供下载:
PhotoSelTaker.java:

/**
  * Created by zjp on 2018/1/24 09:21.
  * 定义一个照片选择器,防止一个Activity有太多的代码,影响可读性
  */
 public class PhotoSelTaker {
       public static final int TAKE_PICTURE = 0; // 拍照
       public static final int ALBUM_PICTURE = 1; // 从相册选取
       public static final int IMG_CUT_FINISHED = 2;

       public void onActivityResult(int requestCode, int resultCode, Intent data) {
             if (resultCode == RESULT_CANCELED) {
                return;
             }

            switch (requestCode) {
                 case TAKE_PICTURE:
                     File f = new File(camera_path);
                     cutPhoto(Uri.fromFile(f));
                     break;
                 case ALBUM_PICTURE:
                     if (Constans.toUploadimgs != null) {
                         for (String imgpath :Constans.toUploadimgs) {
                               String path = FileUtils.compressImageView(mContext, imgpath); //压缩图片,实战过,图片压缩到500k以下,很清楚,but有点耗时
                               BitmapFactory.Options options = new BitmapFactory.Options();
                               options.inPreferredConfig = Bitmap.Config.RGB_565;
                               options.inSampleSize = 5;
                               Bitmap photo = BitmapFactory.decodeFile(imgpath, options);
                               addPhotoImage(photo, path);
                         }
                     }
       }

       public void addPhotoImage(Bitmap bitmap, String path) {
            addPhotoImage2(bitmap, path);
       }

       private void addPhotoImage2(Bitmap bitmap, String path) {
            View imgView = View.inflate(mContext, R.layout.item_photo, null);
       //        imgView.setTag(path);

            ImageView img = (ImageView) imgView.findViewById(R.id.img);
            img.setImageBitmap(bitmap);

            mAddPhotoGridLayout.addPhoto(imgView); //显示图片
            Constans.bitmapPathList.add(path);
       }

     ……此处省略n行代码

       public void showDialog() {
              String[] stringItems = mContext.getResources().getStringArray(R.array.select_img_item);
              final ActionSheetDialog dialog = new ActionSheetDialog(mContext, stringItems, null);
              dialog.isTitleShow(false)
                    .itemTextColor(mContext.getResources().getColor(R.color.title_color))
                    .cancelText(mContext.getResources().getColor(android.R.color.black))
                    .show();
              dialog.setOnOperItemClickL(new OnOperItemClickL() {
              @Override
              public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                       case 0:
                            takephoto();
                       break;
                       case 1:
                            Intent it = new Intent();
                            it.setClass(mContext, AlbumActivity.class);//跳转至AlbumActivity选择照片这个类
                            it.putExtra("maxnum", (9 - getCurBitmapCount())); //最多可以选9张
                            mContext.startActivityForResult(it, ALBUM_PICTURE);
                            dialog.dismiss();
                       break;
                    }
                  dialog.dismiss();
           }
         });
       }
}

AlbumActivity这个类我也不贴了,代码量比较大,如果感兴趣,请到我的github下载。

下面主Activity如何调用它,看下面:

public class MainActivity extends AppCompatActivity implements AddPhotoGridLayout.AddPhotoCallback{

     private  AddPhotoGridLayout mAddPhoto;

     private PhotoSelTaker photoSelTaker;

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (null != photoSelTaker)
                 photoSelTaker.onActivityResult(requestCode, resultCode, data); //这里一定调用photoSelTaker中的onActivityResult()方法,不然点击完图片,返回的图片不显示
          super.onActivityResult(requestCode, resultCode, data);
     }

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         mAddPhoto = (AddPhotoGridLayout) findViewById(R.id.addphotogridlayout);

         mAddPhoto.setmAddPhotoCallback(this, 9); //这里可以自定义我们要上传图片的张数,很方便
}

     @Override
     public void onClickAddPhoto() {
         photoSelTaker = new PhotoSelTaker(MainActivity.this);
         mAddPhotoGridLayout = mAddPhoto;
         photoSelTaker.showDialog();
     }
} 

主Activity就这几行代码,就可以成功完成多张图片上传,并且是用GridLayout实现,是不是很方便呢,如果大家喜欢这篇文字,请留下你的赞,我会继续努力!

相关文章

网友评论

  • 大BO啫:大佬,你忘记附上你GIT的地址了

本文标题:被遗忘的GridLayout展示九宫格(仿照微信上传多张图片)

本文链接:https://www.haomeiwen.com/subject/yeteaxtx.html