AndroidStudio实现仿微信多图上传、删除

最近一直在忙项目很久没写博客了。今天补上最近遇到的问题。

前两天说要实现一个点击图片选择或者从相册上传图片,然后这个选择框自动后移以为。但最多上传四种。类似这种。

点击减号可以对应删除图片。图片显示就有gridview就行了上代码:

public class GridViewAddImageAdapter extends BaseAdapter {
    private List<Map<String, Object>> datas;
    private Context context;
    private LayoutInflater inflater;
    /**
     * 可以动态设置最多上传几张,之后就不显示+号了,用户也无法上传了
     * 默认5张
     */
    private int maxImages = 5;

    public GridViewAddImageAdapter(List<Map<String, Object>> datas, Context context) {
        this.datas = datas;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    /**
     * 获取最大上传张数
     *
     * @return
     */
    public int getMaxImages() {
        return maxImages;
    }

    /**
     * 设置最大上传张数
     *
     * @param maxImages
     */
    public void setMaxImages(int maxImages) {
        this.maxImages = maxImages;
    }

    /**
     * 让GridView中的数据数目加1最后一个显示+号
     *
     * @return 返回GridView中的数量
     */
    @Override
    public int getCount() {
        int count = datas == null ? 1 : datas.size() + 1;
        if (count >= maxImages) {
            return datas.size();
        } else {
            return count;
        }
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    public void notifyDataSetChanged(List<Map<String, Object>> datas) {
        this.datas = datas;
        this.notifyDataSetChanged();

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {


        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        if (datas != null && position < datas.size()) {
            final File file = new File(datas.get(position).get("path").toString());
            Glide.with(context)
                    .load(file)
                    .priority(Priority.HIGH)
                    .into(viewHolder.ivimage);
            viewHolder.btdel.setVisibility(View.VISIBLE);
            viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (file.exists()) {
                        file.delete();
                    }
                    datas.remove(position);
                    notifyDataSetChanged();
                }
            });
        } else {

            Glide.with(context)
                    .load(R.drawable.tianjiazhaopian)
                    .priority(Priority.HIGH)
                    .centerCrop()
                    .into(viewHolder.ivimage);
            viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
            viewHolder.btdel.setVisibility(View.GONE);
        }

        return convertView;

    }

    public class ViewHolder {
        public final ImageView ivimage;
        public final Button btdel;
        public final View root;

        public ViewHolder(View root) {
            ivimage = (ImageView) root.findViewById(R.id.iv_image);
            btdel = (Button) root.findViewById(R.id.bt_del);
            this.root = root;
        }
    }
}

这里的datas就是我们传入的图片资源路径。 

 

gradview显示样式,就是一个显示图片的imageview一个控制删除的button

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/iv_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:gravity="center"
            android:scaleType="centerCrop" />

        <Button
            android:id="@+id/bt_del"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/btn_add_img_delete" />
    </RelativeLayout>

</RelativeLayout>

在要显示的界面的布局文件添加gridview,然后初始化。


            <GridView
                android:id="@+id/xzcp_gridview"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_toRightOf="@id/tv_cptupian"
                android:columnWidth="80dp"
                android:horizontalSpacing="5dp"
                android:numColumns="4" />
 gridViewAddImageAdapter = new GridViewAddImageAdapter(datas, getActivity());
        mGridView.setAdapter(gridViewAddImageAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showDialog();
            }
        });

dialog就是我们显示选择图片来源。

 public void showDialog() {
        View localView = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_photo, null);
        TextView tv_camera = (TextView) localView.findViewById(R.id.register_dialog_photograph);
        TextView tv_gallery = (TextView) localView.findViewById(R.id.register_dialog_album);
        TextView tv_cancel = (TextView) localView.findViewById(R.id.register_dialog_cannel);
        dialog = new Dialog(getActivity(), R.style.ModifyDialog);
        dialog.setContentView(localView);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        // 设置全屏
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = display.getWidth(); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });

        tv_camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                // 拍照
                takePhoto();
            }
        });

        tv_gallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                // 从系统相册选取照片
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, CHOOSE_PHOTO);
                dialog.dismiss();
            }
        });
    }

    //拍照
    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, TAKE_PHOTO);
    }

    //获得照片名字
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return "IMG_" + dateFormat.format(date);
    }

    //开启剪裁
    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            SaveImage(photo);
        }
    }

    //保存图片
    public void SaveImage(Bitmap bitmap) {

        /*将bitmap保存下来*/
        /* 将Bitmap设定到ImageView */

        File filest = new File(Environment.getExternalStorageDirectory() + "/path");
        if (!filest.exists()) {
            boolean resyltBool = filest.mkdirs();
        }

        File file = new File(Environment.getExternalStorageDirectory() + "/path/" + getPhotoFileName() + ".jpg");


        Log.d(TAG, "SaveImage: file:" + file.getName());
        Log.d(TAG, "SaveImage: file:" + file.getAbsolutePath());
        Map<String, Object> map = new HashMap<>();
        map.put("path", file.getAbsolutePath());

        datas.add(map);
        gridViewAddImageAdapter.notifyDataSetChanged(datas);
        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream);
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

把图片路径存入datas里面。

private List<Map<String, Object>> datas;
//临时图片路径
private File tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());

在onActivityResult中

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    //照相
                    startPhotoZoom(Uri.fromFile(tempFile), 15);
                    break;
                case CHOOSE_PHOTO:
                    if (data != null)
                        startPhotoZoom(data.getData(), 150);
                    //相册
                    break;
                case PHOTO_REQUEST_CUT:
                    //剪裁并设置头像
                    if (data != null)
                        setPicToView(data);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

 

发布了29 篇原创文章 · 获赞 6 · 访问量 2万+
展开阅读全文

Android更换头像问题,点击拍照或者从相册中选择没有返应。求助!

04-07

package com.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.activity.R; /** * 头像获取方式选择弹出框 */ public class SetToTakePicActivity extends Activity { public static final String INTENT_KEY_BUTTON_TYPE = "ButtonType"; public static final String BUTTON_TYPE_TAKE_PICTURES = "TAKE_PICTURES"; public static final String BUTTON_TYPE_FROM_ALBUM = "FROM_ALBUM"; public static final String BUTTON_TYPE_NUM = "NUM"; private String num; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set_headpic); View btnTakePics = findViewById(R.id.btn_take_pictures); View btnFromAlbum = findViewById(R.id.btn_from_album); View btnCancel = findViewById(R.id.btn_cancel); btnTakePics.setOnClickListener(new mOnClickListener()); btnFromAlbum.setOnClickListener(new mOnClickListener()); btnCancel.setOnClickListener(new mOnClickListener()); num = getIntent().getStringExtra("num"); } class mOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_take_pictures: Intent intent = new Intent(); intent.putExtra(INTENT_KEY_BUTTON_TYPE, BUTTON_TYPE_TAKE_PICTURES); intent.putExtra(BUTTON_TYPE_NUM, num); setResult(Activity.RESULT_OK, intent); finish(); break; case R.id.btn_from_album: intent = new Intent(); intent.putExtra(INTENT_KEY_BUTTON_TYPE, BUTTON_TYPE_FROM_ALBUM); intent.putExtra(BUTTON_TYPE_NUM, num); setResult(Activity.RESULT_OK, intent); finish(); break; case R.id.btn_cancel: finish(); break; default: break; } } } } 问答

如何使用android studio将上传到服务器?

08-12

<div class="post-text" itemprop="text"> <p>I'm trying to upload an image, taken from an image view, in a directory on my altervista server.</p> <p>I saw a lot of questions like this but they use HttpClient, HttpPost etc. that are now deprecated. I saw a tutorial on Youtube and I adapted it to my app but it's not working. The code uploads the image in the right directory, but if I try to open it on the server, I get a black screen. I downloaded the image on my pc and the result is worse.</p> <p><a href="https://i.stack.imgur.com/piOez.png" rel="nofollow noreferrer">Here what I see when I download the image</a></p> <p><a href="https://i.stack.imgur.com/QB4qt.jpg" rel="nofollow noreferrer">Here the image, that is empty</a></p> <p>Php code:</p> <pre><code> <?php $image=$_POST['image']; $decodedImage=base64_decode("$image"); file_put_contents("/membri/motivationalapp/shareImages/" . "prova" . ".jpg", $decodedImage); echo "ok"; ?> </code></pre> <p>The image is taken from an imageView:</p> <pre><code> imageView=findViewById(R.id.imageView); screenShot=((BitmapDrawable)imageView.getDrawable()).getBitmap(); </code></pre> <p>The thread that encodes the image:</p> <pre><code> new Thread(new Runnable() { Background background = new Background(MotAct.this); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); public void run() { screenShot.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream); String encodedImage= Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT); Log.d("debug", encodedImage); background.uploadShareImage(encodedImage); //call to AsyncTask } }).start(); </code></pre> <p>The upload of the image in the Asynctask class: doInBackground Method:</p> <pre><code> final String urlServer = "http://aaa.altervista.org/fileUp/shareImage.php"; encodedImage=strings[1]; try { //connecting to server url = new URL(urlServer); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); OS = httpURLConnection.getOutputStream(); bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8")); //encode data for post method String dati = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(encodedImage, "UTF-8"); bufferedWriter.write(dati); bufferedWriter.flush(); bufferedWriter.close(); OS.close(); //read server answer InputStream inputStream = httpURLConnection.getInputStream(); bufferedReader= new BufferedReader(new InputStreamReader((inputStream))); stringBuilder= new StringBuilder(); while((risposta=bufferedReader.readLine())!=null){ stringBuilder.append(risposta+" "); } bufferedReader.close(); inputStream.close(); inputStream.close(); httpURLConnection.disconnect(); risposta=stringBuilder.toString().trim(); if(risposta.equals("ok")) return 1; else return 100; }catch (MalformedURLException e){ e.printStackTrace(); } catch (IOException e1){ e1.printStackTrace(); } </code></pre> <p>Hope you guys can help me. Thanks</p> </div> 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览