两千行代码高仿微信发布朋友圈

2019年 的第一个工作日 祝大家新年快乐 希望这一年 依旧拥有一颗感恩的心
这次时间很长 前后做了一个星期 这次做的是我自己的项目 代码有点多 写的时候没有注释 这次就当整理一下思路 这些代码均可运行 无bug
有两个Fragment 第一个fragment用来显示 发布页面 ,并且跳转到拍照和选择 相册
第二个 主要是用来查看 之前的页面
两千行代码高仿微信发布朋友圈_第1张图片
用到了知乎的开源库 matisse 和 另一个google员工写的photoView
第一个Fragment

要注意的是 photo要使用的话 必须在 父布局 设置一下触摸拦截 可以深入了解一下 view的事件分发机制
第二 就是 安卓7.0以后的文件在不同的应用程序之间 不能够随意访问了 要使用contentProvider
而且要动态获取权限

public class UploadFragment extends Fragment  implements View.OnClickListener {
//    返回码
    private static final int REQUEST_CODE_CHOOSE = 23;
    private ArrayList mDataUri = new ArrayList<>();
    private ViewImageFragment.OnFragmentInteractionListener mListener;
    private Context mContext;
    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;
    //    private uploadActivity.UriAdapter mAdapter;
    private LinearLayout ImageContainer ,root;
    private FrameLayout chooseMethod;
    private boolean open = false;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private int LastId = 0;

    private boolean popupWindowIsShow = false;

    private PopupWindow popupWindow;

    private String mParam1;
    private String mParam2;
        @Override
//
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
//
    public UploadFragment() {
        // Required empty public constructor
    }


    //   内部接口
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(WhatDo wd);
    }
    public static UploadFragment newInstance(String param1, String param2) {
        UploadFragment fragment = new UploadFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
//
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View  view  =  inflater.inflate(R.layout.fragment_upload, container, false);
        ImageContainer = view.findViewById(R.id.imageContainer);
        root = view.findViewById(R.id.uploadView);
        DisplayMetrics dm = this.getWH();
//        Log.i("testW",""+dm.widthPixels);
        ImageView imageView = new ImageView(getActivity());
        ViewGroup.LayoutParams  params = new ViewGroup.LayoutParams(200,200);
        LinearLayout uploadView = view.findViewById(R.id.uploadView);
//        添加的是下面的那个按钮
        uploadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(open){
                    chooseMethod.setVisibility(View.GONE);
                    open = false;
                }
            }
        });
        imageView.setLayoutParams(params);
        imageView.setImageResource(R.drawable.ic_add);
//        imageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (open){
//
//                }else {
//                    chooseMethods();
//                    open = true;
//                }
//            }
//        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopWindow(v);
            }
        });
        chooseMethod = view.findViewById(R.id.chooseMethod);
        chooseMethod.setVisibility(View.GONE);
//        添加打开的监听
        TextView takePhoto = view.findViewById(R.id.takePhoto);
        takePhoto.setOnClickListener(this);
        TextView fromGallery = view.findViewById(R.id.fromGallery);
        fromGallery.setOnClickListener(this);
        ImageContainer.addView(imageView);
        return view;
    }
    //动态添加 图片
    public void  AddImage(List uris){
        DisplayMetrics dm = this.getWH();
//        Log.i("testW",""+dm.widthPixels);
//        if(uris==null){
//            ImageView imageView = new ImageView(getActivity());
//            ViewGroup.LayoutParams  params = new ViewGroup.LayoutParams(200,200);
//            imageView.setLayoutParams(params);
//            imageView.setImageResource(R.drawable.ic_add);
////            Glide.with(getActivity()).load(files.get(i)).into(imageView);
//            imageView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (open){
//
//                    }else {
//                        chooseMethods();
//                        open = true;
//                    }
//                }
//            });
//            ImageContainer.addView(imageView);
//        }
        int count = uris.size();
        ViewGroup.LayoutParams  params = new ViewGroup.LayoutParams(200,200);
        for (int i = 0+LastId; i () {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            switch (v.getId()) {
                                case R.id.fromGallery:
                                    Matisse.from(getActivity())
                                            .choose(MimeType.ofAll(), false)
                                            .countable(true)
//                    .capture(true)
                                            .captureStrategy(
                                                    new CaptureStrategy(true, "com.zhihu.matisse.sample.fileprovider","test"))
                                            .maxSelectable(9)
                                            .addFilter(new GifSizeFilter(320, 320, 5 * com.zhihu.matisse.filter.Filter.K * com.zhihu.matisse.filter.Filter.K))
                                            .gridExpectedSize(
                                                    getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                                            .thumbnailScale(0.85f)
//                                            .imageEngine(new GlideEngine())  // for glide-V3
                                            .imageEngine(new Glide4Engine())    // for glide-V4
                                            .setOnSelectedListener(new OnSelectedListener() {
                                                @Override
                                                public void onSelected(
                                                        @NonNull List uriList, @NonNull List pathList) {
                                                    // DO SOMETHING IMMEDIATELY HERE
                                                    Log.e("onSelected", "onSelected: pathList=" + pathList);

                                                }
                                            })
                                            .originalEnable(true)
                                            .maxOriginalSize(10)
                                            .autoHideToolbarOnSingleTap(true)
                                            .setOnCheckedListener(new OnCheckedListener() {
                                                @Override
                                                public void onCheck(boolean isChecked) {
                                                    // DO SOMETHING IMMEDIATELY HERE
                                                    Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                                                }
                                            })
                                            .forResult(REQUEST_CODE_CHOOSE);
                                    break;
                                case R.id.takePhoto:
                                    if( checkPerssion()){
                                        takePhoto();
                                    }else {
                                        Log.i("camera","失败");
                                    }
                                    break;
                                default:
                                    break;
                            }
//                mAdapter.setData(null, null);
                        } else {
                            Toast.makeText(getActivity(), R.string.permission_request_denied, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private Boolean checkPerssion(){

        if(ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
//                检查权限
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    CAMERA_REQUEST_CODE
            );
            return true;
        }else {//权限已经获取
            return true;
        }

    }
    //    拍照
    private void  takePhoto(){
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        // 拍照的照片的存储位置
        String mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
//                    文件转为URL地址
/*可以看到 getUriForFile(),需要传入 一个
authority 的参数,这正是我们前面在 AndroidManifest.xml 文件中配置的 android:authorities 参数
调用这个方法会自动得到一个 file:// 转换成 content:// 的一个 Uri 对象,可以供我们直接使用 */
        // 照片所在的Uri地址
        Uri imageUri = FileProvider.getUriForFile(mContext,

                mContext.getApplicationContext().getPackageName() + ".my.provider",
                new File(mTempPhotoPath));
//                    设置系统相机的图片地址
        //下面这句指定调用相机拍照后的照片存储的路径

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent,0);
        Log.i("camera","失败6");
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(open){
                chooseMethod.setVisibility(View.GONE);
                open = false;
            }
        }
    };
    /**
     * 显示popwindow的布局方法
     * @param view
     */
    private void showPopWindow(View view){
        if(popupWindowIsShow){
            return;
        }
        View contentView = LayoutInflater.from(getActivity())
                .inflate(R.layout.popwindow_layout,null,false);
        popupWindow = new PopupWindow(contentView,ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        TextView tp = contentView.findViewById(R.id.takePhoto);
        tp.setOnClickListener(this);
        TextView fg = contentView.findViewById(R.id.fromGallery);
        fg.setOnClickListener(this);
//        仿写
        //产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().setAttributes(lp);
        //点击外面popupWindow消失
        popupWindow.setOutsideTouchable(true);
        // popwindow 获取焦点
        //设置popupWindow消失时的监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            //在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
                popupWindowIsShow = false;
            }
        });
//
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
//        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_add));
//        int widthPixels = (int) (getWH().widthPixels*0.7);
//        int heightPixels = (int) (getWH().heightPixels*0.2);
//        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(widthPixels,heightPixels);
//        contentView.setLayoutParams(params);
        popupWindow.showAtLocation(root,Gravity.CENTER,0,0);
        popupWindowIsShow= true;

    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        if (context instanceof ViewImageFragment.OnFragmentInteractionListener) {
            mListener = (ViewImageFragment.OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    /**
     * 这个方法是用来在拍照返回或者相册返回时dismiss掉pop
     */
    @Override
    public void onResume() {
        super.onResume();
        if(popupWindowIsShow){
            popupWindow.dismiss();
            popupWindowIsShow=false;
        }
    }
}


第二个Fragment 实际上是一个图片查看的组件 因为如果用activity的话 太重了
public class ViewImageFragment extends Fragment {
private ViewPager viewPager;
GestureDetector detector;
private Context mContext;
private ArrayList mDataUri = new ArrayList<>();

private static final String ARG_PARAM1 =  "param1";
private static final String ARG_PARAM2 = "param2";

//newInstance 执行之后获取的数据
private ArrayList mDataFile = new ArrayList<>();
private int iWantToDispaly;

public ViewImageFragment() {
    // Required empty public constructor
}

public static ViewImageFragment newInstance(ArrayList param, int currentPoint ) {
    ViewImageFragment fragment = new ViewImageFragment();
    int count = param.size();
    Bundle args = new Bundle();
    for (int i = 0; i 

// Log.i(“count”, String.valueOf(mDataFile.get(2)));
// mParam1 = getArguments().getParcelableArrayList(ARG_PARAM1);
iWantToDispaly = getArguments().getInt(“currentPoint”);
}
// initData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewimage, container, false);
viewPager = (ViewPager) view.findViewById(R.id.vp);
viewPager.setAdapter(new MyPagerAdapter(getActivity(),mDataFile));
viewPager.setCurrentItem(iWantToDispaly);
return view;
}
//因为是在一个activity中 ,这个函数可以 不调用

public void onButtonPressed(Uri uri) {

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
}


class MyPagerAdapter extends PagerAdapter {
    private Context mContext;
    private List mData;

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

    @SuppressLint("ClickableViewAccessibility")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = View.inflate(mContext, R.layout.layout_viewimage,null);
        final PhotoView imageView = (PhotoView) view.findViewById(R.id.viewpager_imageview);

// Log.i(“counte”, String.valueOf(mData.get(position)));
// 使用bitmap方法
// Bitmap bitmap = BitmapFactory.decodeFile(mData.get(position).getAbsolutePath());
// imageView.setImageBitmap(bitmap);

        Glide.with(getActivity()).load(mData.get(position)).into(imageView);
        imageView.setOnPhotoTapListener(new OnPhotoTapListener(){
            @Override
            public void onPhotoTap(ImageView view, float x, float y) {
                OnFragmentInteractionListener listener = (OnFragmentInteractionListener) mContext;
                if(imageView.getAttacher().getScale()==1f){
                    listener.onFragmentInteraction(new WhatDo("remove",0));
                }else {

//
}
}
});

        container.addView(view);
        return view;
    }
    public MyPagerAdapter(Context mContext, List mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }
}

public interface OnFragmentInteractionListener {
    void onFragmentInteraction(WhatDo wd);
}

}

你可能感兴趣的:(android)