美文网首页Android知识
Android实现既能相册选择、拍照选择,点击每张图片又能放大查

Android实现既能相册选择、拍照选择,点击每张图片又能放大查

作者: 破荒之恋 | 来源:发表于2017-10-27 10:52 被阅读331次

最近很长一段时间没有更新博客了!实在是比较忙!最近需要使用一个功能:选择本机相册或者拍照返回图片显示到九宫格中,并且可以点击九宫格每一张放大查看、滑动等功能!

在网上也看到一些大神写的demo和第三方库,不过发现很多都不完整,有的只是实现相册选择,没有实现拍照功能;有的实现了相册和拍照功能又没有实现点击放大查看滑动功能;所以我就跟据那些demo完善了一下,实现既能相册选择、拍照选择,点击每张图片又能放大查看!现在来看看怎么实现的!

来看看效果图吧!

image.png image.png image.png

使用到的依赖库是

compile 'me.iwf.photopicker:PhotoPicker:0.1.8'

来看看首页的布局:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.an.myphotodemo.MainActivity">

  


    <com.an.myphotodemo.NoScrollGridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/view_gad"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:layout_marginTop="3dp"
        android:numColumns="3"

        android:scrollbars="none"
        android:verticalSpacing="3dp"
        android:id="@+id/recycler_view"/>


</LinearLayout>

NoScrollGridView 是自定义的一个ScrollGridView
public class NoScrollGridView extends GridView {
    public NoScrollGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public NoScrollGridView(Context context) {
        super(context);
    }
    public NoScrollGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

对了,还需要一些工具类,后面再说,现在来看看主要实现的代码!

首页oncreate()中NoScrollGridView初始化并且设置适配器

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        itemLayout = (NoScrollGridView) findViewById(R.id.recycler_view);

        ninePicturesAdapter = new NinePicturesAdapter(this, 9, new NinePicturesAdapter.OnClickAddListener() {
            @Override
            public void onClickAdd(int positin) {
                choosePhoto();
            }
        }, new NinePicturesAdapter.OnItemClickAddListener() {
            @Override
            public void onItemClick(int positin) {

                Log.i(TAG, "-------------onItemClick: "+positin);

                String[] array = new String[ninePicturesAdapter.getPhotoCount()];
                // List转换成数组
                for (int i = 0; i < photossss.size()-1; i++) {
                    array[i] = photossss.get(i);
                }
                //数组转换为集合
                //List<String> stringsss = Arrays.asList(array);

                Log.i(TAG, "----array:--- "+array.length);
                imageBrower(positin,array);
            }
        });
        itemLayout.setAdapter(ninePicturesAdapter);

    }

/**
* 开启图片选择器choosePhoto()
*/

    private void choosePhoto() {
        PhotoPickerIntent intent = new PhotoPickerIntent(MainActivity.this);
        intent.setPhotoCount(9);
        intent.setShowCamera(true);
        startActivityForResult(intent, REQUEST_CODE);

        //ImageLoaderUtils.display(context,imageView,path);
    }

/**
* 每一张图片放大查看
* @param position
* @param urls
*/

    private void imageBrower(int position, String[] urls) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量,一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

/**
* 接受返回的图片数据 :onActivityResult()
* @param requestCode
* @param resultCode
* @param data
*/

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    Log.i(TAG, "----------onActivityResult: "+ photos.get(i));
                }
                    if(ninePicturesAdapter!=null) {
                        Log.i(TAG, "----------photossss: ========");
                        ninePicturesAdapter.addAll(photos);
          
                      //获取九宫格显示的所有图片数据
                        photossss = ninePicturesAdapter.getData();
                        Log.i(TAG, "----------photossss: ========"+photossss.size());
                        
                    }
            }
        }
    }

到这里主页代码已经完成了,现在来看看适配器是如何完成的NinePicturesAdapter
/**

  • des:9宫图适配器
  • Created by an
  • on 2016.09.16:33
    */


public class NinePicturesAdapter extends BaseAblistViewAdapter<String> {
    private boolean showAdd = true;
    private int picturnNum = 0;
    private boolean isDelete = false;//当前是否显示删除按钮
    private OnClickAddListener onClickAddListener;
    private OnItemClickAddListener onItemClickListener;
    private boolean isAdd=true;//当前是否显示添加按钮


    private static final String TAG = "NinePicturesAdapter";
    public NinePicturesAdapter(Context context, int picturnNum, OnClickAddListener onClickAddListener,OnItemClickAddListener onItemClickListener) {
        super(context);
        this.picturnNum = picturnNum;
        this.onClickAddListener = onClickAddListener;
        this.onItemClickListener=onItemClickListener;
        showAdd();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_grid_photo, parent, false);
        }
        final ImageView imageView = ViewHolderUtil.get(convertView, R.id.img_photo);
        ImageView imgDelete = ViewHolderUtil.get(convertView, R.id.img_delete);
        final String url = getData().get(position);
        //显示图片
        if (TextUtils.isEmpty(url) && showAdd) {
            ImageLoaderUtils.display(mContext, imageView, R.drawable.addphoto);
            imgDelete.setVisibility(View.GONE);
        } else {
            imgDelete.setVisibility(View.VISIBLE);
            ImageLoaderUtils.display(mContext, imageView, url);
        }

        autoHideShowAdd();

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //再次选择图片
                if (TextUtils.isEmpty(url)) {
                    if (onClickAddListener != null) {
                        onClickAddListener.onClickAdd(position);
                    }
                } else {
                    //放大查看图片

                    onItemClickListener.onItemClick(position);
                    Log.i(TAG, "onClick: "+position);
                    //BigImagePagerActivity.startImagePagerActivity((Activity) mContext, getData(), position);
                }
            }
        });
        //删除按钮
        imgDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                remove(position);
                if (!isDelete && getCount() < 1) {
                    add("");
                    isDelete = true;
                }
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    @Override
    public void setData(List<String> d) {
        boolean hasAdd=false;
        for (int i = 0; i < d.size(); i++) {
            if(TextUtils.isEmpty(d.get(i))){
                hasAdd=true;
                break;
            }
        }
        super.setData(d);
        if(!hasAdd){
            showAdd();
        }
    }

    @Override
    public void addAll(List<String> d) {
        if(isAdd){
            HideAdd();
        }
        super.addAll(d);
        showAdd();
    }

    /**
     * 移除add按钮
     */
    public void autoHideShowAdd(){
        int lastPosition=getData().size()-1;
            if(lastPosition==picturnNum&&getData().get(lastPosition)!=null&& TextUtils.isEmpty(getData().get(lastPosition))){
                getData().remove(lastPosition);
                isAdd=false;
                notifyDataSetChanged();
            }else if(!isAdd){
                showAdd();
            }
    }
    /**
     * 移除add按钮
     */
    public void HideAdd(){
        int lastPosition=getData().size()-1;
        if(getData().get(lastPosition)!=null&& TextUtils.isEmpty(getData().get(lastPosition))){
            getData().remove(lastPosition);
            isAdd=false;
            notifyDataSetChanged();
        }
    }
    /**
     * 显示add按钮
     */
    public void showAdd(){
        if(getData().size()<picturnNum){



            addAt(getData().size(),"");
            isAdd=true;
            notifyDataSetChanged();
        }
    }

    /**
     * 获取图片张数
     * @return
     */
   public int getPhotoCount(){
       return isAdd==true?getCount()-1:getCount();
   }


    /**
     * 加号接口
     */
    public interface OnClickAddListener {
        void onClickAdd(int positin);
    }

    public interface OnItemClickAddListener {
        void onItemClick(int positin);
    }

}

适配器加载的布局如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/rr_gad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <ImageView
            android:id="@+id/img_photo"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:scaleType="centerCrop" />

    </RelativeLayout>
    <ImageView
        android:id="@+id/img_delete"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignRight="@+id/rr_gad"
        android:layout_alignTop="@+id/rr_gad"
        android:background="@drawable/cha" />
</RelativeLayout>

ImageLoaderUtils是一个图片加载显示的工具类,当然也可以使用其他的

至此:相册选择和拍照功能、显示九宫图皆以实现,现在来看看图片放大查看:布局如下image_detail_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.an.myphotodemo.image.HackyViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <TextView
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="center"
        android:textSize="18sp"
        android:textColor="@android:color/white"
        android:text="@string/viewpager_indicator"
        android:background="@android:color/transparent" />

</FrameLayout>

查看图片滑动主业如下:

public class ImagePagerActivity extends FragmentActivity {
    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    public static final String EXTRA_IMAGE_URLS = "image_urls";

    private HackyViewPager mPager;
    private int pagerPosition;
    private TextView indicator;

    private static final String TAG = "ImagePagerActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_detail_pager);

        pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
        String[] urls = getIntent().getStringArrayExtra(EXTRA_IMAGE_URLS);

        Log.i(TAG, "length: "+urls.length);


        mPager = (HackyViewPager) findViewById(R.id.pager);
        ImagePagerAdapter mAdapter = new ImagePagerAdapter(
                getSupportFragmentManager(), urls);
        mPager.setAdapter(mAdapter);
        indicator = (TextView) findViewById(R.id.indicator);

        CharSequence text = getString(R.string.viewpager_indicator, 1, mPager
                .getAdapter().getCount());
        indicator.setText(text);
        // 更新下标
        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                CharSequence text = getString(R.string.viewpager_indicator,
                        arg0 + 1, mPager.getAdapter().getCount());
                indicator.setText(text);
            }

        });
        if (savedInstanceState != null) {
            pagerPosition = savedInstanceState.getInt(STATE_POSITION);
        }

        mPager.setCurrentItem(pagerPosition);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

        public String[] fileList;

        public ImagePagerAdapter(FragmentManager fm, String[] fileList) {
            super(fm);
            this.fileList = fileList;
        }

        @Override
        public int getCount() {
            return fileList == null ? 0 : fileList.length;
        }

        @Override
        public Fragment getItem(int position) {
            String url = fileList[position];
            return ImageDetailFragment.newInstance(url);
        }

    }
}

这里就结束了,想了解更多的点这里:
https://github.com/caichengan/MyPhotoDemo

相关文章

网友评论

    本文标题:Android实现既能相册选择、拍照选择,点击每张图片又能放大查

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