android 多图片上传

时间:2020-01-09
本文章向大家介绍android 多图片上传,主要包括android 多图片上传使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

recyclerview item布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RelativeLayout android:layout_marginRight="15dp" android:layout_width="95dp" android:layout_height="85dp" android:layout_centerInParent="true"> <ImageView android:layout_marginRight="5dp" android:id="@+id/fiv" android:layout_width="85dp" android:layout_height="80dp" android:layout_marginTop="6dp" android:contentDescription="@null" android:scaleType="centerCrop" android:src="@color/cus_view_detail_lines" /> <LinearLayout android:id="@+id/ll_del" android:layout_width="25dp" android:layout_height="25dp" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:gravity="end" android:orientation="vertical"> <ImageView android:id="@+id/iv_del" android:layout_width="20dp" android:layout_height="20dp" android:contentDescription="@null" android:scaleType="fitXY" android:src="@mipmap/red" /> </LinearLayout> <ImageView android:id="@+id/iv_duration" android:layout_width="80dp" android:layout_height="80dp" android:scaleType="centerCrop" /> </RelativeLayout> </RelativeLayout>

 

可能写的不太好但是作为一种总结吧 这是最初版本  我没时间修改  等我有时间我会精修的 本文比较粗糙 

 

  

横屏
<?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="@color/color_white"> <include android:id="@+id/include" layout="@layout/title" /> <Button android:id="@+id/bt_put" android:layout_width="match_parent" android:layout_height="34dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginLeft="96dp" android:layout_marginTop="10dp" android:layout_marginRight="84dp" android:layout_marginBottom="10dp" android:background="@drawable/btn_background" android:text="提交" android:textColor="@color/color_white" android:textSize="15sp" /> <ScrollView android:id="@+id/scroview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/bt_put" android:layout_below="@+id/include" android:orientation="vertical" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_white" android:orientation="horizontal"> <RelativeLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="3.5"> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:text="您的手机号、QQ号、邮箱是?" android:textColor="@color/black" android:textSize="17sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="11dp" android:layout_toRightOf="@id/tv_phone" android:text="(选填)" android:textSize="14sp" /> <EditText android:id="@+id/et_phone" android:layout_width="500dp" android:layout_height="50dp" android:layout_marginLeft="30dp" android:layout_marginTop="50dp" android:background="@drawable/under_line_transparent" android:hint="填写多种联系方式时,请用逗号分隔。" android:imeOptions="actionDone" android:inputType="number" android:paddingLeft="20dp" android:paddingRight="20dp" android:textSize="14sp" /> <TextView android:id="@+id/tv_question" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:text="问题/意见描述" android:textColor="@color/black" android:textSize="17sp" /> <TextView android:id="@+id/tv_required" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:layout_marginLeft="5dp" android:layout_marginTop="30dp" android:layout_toRightOf="@id/tv_question" android:text="(必填)" android:textSize="14sp" /> <TextView android:id="@+id/tv_sumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:layout_marginLeft="285dp" android:layout_marginTop="30dp" android:layout_toRightOf="@id/tv_required" android:text="(0/300)" android:textSize="14sp" /> <EditText android:id="@+id/et_input" android:layout_width="500dp" android:layout_height="123dp" android:layout_below="@id/tv_question" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:background="@drawable/under_line_transparent" android:gravity="top" android:hint="请留下您宝贵的意见,字数不少于10个字" android:imeOptions="actionDone" android:maxLength="300" android:paddingLeft="20dp" android:paddingTop="10dp" android:paddingRight="20dp" android:paddingBottom="10dp" android:textSize="14sp" /> </RelativeLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical"> <TextView android:id="@+id/tv_sc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginLeft="13dp" android:text="上传图片" android:textColor="@color/black" android:textSize="17sp" /> <TextView android:id="@+id/tv_get_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="(选填,您可以上传3张)" android:textSize="14sp" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="15dp" android:layout_marginRight="10dp" android:overScrollMode="never" /> </LinearLayout> </LinearLayout> </ScrollView> </RelativeLayout>

  


竖屏
<?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="@color/color_white"> <include android:id="@+id/include" layout="@layout/titles" /> <Button android:id="@+id/bt_put" android:layout_width="match_parent" android:layout_height="54dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginLeft="22dp" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:layout_marginBottom="5dp" android:background="@drawable/btn_background" android:text="提交" android:textColor="@color/color_white" android:textSize="18sp" /> <ScrollView android:id="@+id/scroview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/bt_put" android:layout_below="@+id/include" android:orientation="vertical" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_white" android:orientation="horizontal"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="28dp" android:layout_marginTop="10dp" android:text="您的手机号、QQ号、邮箱是?" android:textColor="@color/black" android:textSize="18sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:layout_toRightOf="@id/tv_phone" android:text="(选填)" android:textSize="15sp" /> <EditText android:id="@+id/et_phone" android:layout_width="500dp" android:layout_height="50dp" android:layout_marginLeft="15dp" android:layout_marginTop="50dp" android:layout_marginRight="15dp" android:background="@drawable/under_line_transparent" android:hint="填写多种联系方式时,请用逗号分隔。" android:imeOptions="actionDone" android:inputType="number" android:paddingLeft="20dp" android:paddingRight="20dp" android:textSize="14sp" /> <TextView android:id="@+id/tv_question" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:text="问题/意见描述" android:textColor="@color/black" android:textSize="17sp" /> <TextView android:id="@+id/tv_required" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:layout_marginLeft="5dp" android:layout_marginTop="32dp" android:layout_toRightOf="@id/tv_question" android:text="(必填)" android:textSize="14sp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/et_phone" android:orientation="horizontal"> <TextView android:id="@+id/tv_sumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginTop="30dp" android:layout_marginRight="20dp" android:text="(0/300)" android:textSize="14sp" /> </RelativeLayout> <EditText android:id="@+id/et_input" android:layout_width="500dp" android:layout_height="184dp" android:layout_below="@id/tv_question" android:layout_marginLeft="15dp" android:layout_marginTop="13dp" android:layout_marginRight="15dp" android:background="@drawable/under_line_transparent" android:gravity="top" android:hint="请留下您宝贵的意见,字数不少于10个字" android:imeOptions="actionDone" android:maxLength="300" android:paddingLeft="20dp" android:paddingTop="10dp" android:paddingRight="20dp" android:paddingBottom="10dp" android:textSize="14sp" /> <TextView android:id="@+id/tv_sc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_input" android:layout_marginLeft="17dp" android:layout_marginTop="20dp" android:text="上传图片" android:textColor="@color/black" android:textSize="18sp" /> <TextView android:id="@+id/tv_get_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_input" android:layout_marginLeft="90dp" android:layout_marginTop="23dp" android:text="(选填,您可以上传3张)" android:textSize="14sp" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tv_sc" android:layout_marginLeft="10dp" android:layout_marginTop="15dp" android:layout_marginRight="10dp" android:overScrollMode="never" /> </RelativeLayout> </LinearLayout> </ScrollView> </RelativeLayout>

 

 

主函数

package com.example.zyghfeedback.commits; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.zyghfeedback.R; import com.example.zyghfeedback.assist.FeedbackGlobalManager; import com.example.zyghfeedback.assist.Image; import com.example.zyghfeedback.assist.WeiboDialogUtils; import com.example.zyghfeedback.assist.ZyagUtils; import com.example.zyghfeedback.feebacklist.FeedbackList;; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class CommitsActivity extends Activity implements View.OnClickListener { public static final int CHOOSE_PHOTO = 2;// 相册 //用于横竖屏切换后recyclerview显示行数 private boolean HORIZONTAL_SREEN = false; private RecyclerView recyclerview; private int maxSelectNum = 3;//最多到几张还可以选择 private List<Image> selectList = new ArrayList<>(); private CommitsAdapter adapter; private View include; private ImageView iv_back; //提交按钮 private Button bt_put; private EditText et_phone, et_input; private TextView tv_sumber; private String phone, input; private GridLayoutManager layoutManager; private Dialog mWeiboDialog; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 100) { adapter.notifyDataSetChanged(); } else if (msg.what == 2) { WeiboDialogUtils.closeDialog(mWeiboDialog); AlertDialog.Builder builder = new AlertDialog.Builder(CommitsActivity.this); builder.setTitle("提交成功"); builder.setNegativeButton(("OK"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(CommitsActivity.this, FeedbackList.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); selectList.clear(); dialog.dismiss(); } }); if (!((Activity) CommitsActivity.this).isFinishing()) { AlertDialog dialog = builder.create(); dialog.show(); } } super.handleMessage(msg); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Configuration cf = this.getResources().getConfiguration(); int ori = cf.orientation; if (ori == cf.ORIENTATION_LANDSCAPE) { setContentView(R.layout.feedback_commits); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏 HORIZONTAL_SREEN = true; } else if (ori == cf.ORIENTATION_PORTRAIT) { setContentView(R.layout.feedback_commits); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏 HORIZONTAL_SREEN = false; } setinit(); setonclick(); et_phone.setText(""); et_input.setText(""); } private void setinit() { include = findViewById(R.id.include); iv_back = include.findViewById(R.id.iv_back); bt_put = findViewById(R.id.bt_put); et_phone = findViewById(R.id.et_phone); et_input = findViewById(R.id.et_input); tv_sumber = findViewById(R.id.tv_sumber); recyclerview = findViewById(R.id.recyclerview); //是否为横屏 if (HORIZONTAL_SREEN) { //设置布局管理器 layoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.VERTICAL, false); } else { layoutManager = new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false); } recyclerview.setLayoutManager(layoutManager); //设置adapter adapter = new CommitsAdapter(this, onAddPicClickListener); //添加图片集合 adapter.setList(selectList); //传递上传图片最大个数 adapter.setSelectMax(maxSelectNum); recyclerview.setAdapter(adapter); // adapter.setOnItemClickListener(new CommitsAdapter.OnItemClickListener() { @Override public void onItemClick(int position, View v) { if (selectList.size() > 0) { Image media = selectList.get(position); Toast.makeText(CommitsActivity.this, "暂时不可以哦", Toast.LENGTH_SHORT).show(); } } }); } private void setonclick() { bt_put.setOnClickListener(this); iv_back.setOnClickListener(this); et_input.addTextChangedListener(new TextWatcher() { CharSequence temp; @Override //只要编辑框内容有变化就会调用该方法,s为编辑框变化后的内容 public void onTextChanged(CharSequence s, int start, int before, int count) { temp = s; } @Override //编辑框内容变化之前会调用该方法,s为编辑框内容变化之前的内容 public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override //编辑框内容变化之后会调用该方法,s为编辑框内容变化后的内容 public void afterTextChanged(Editable s) { tv_sumber.setText(("(" + "" + temp.length() + "/" + "300)")); } }); } private CommitsAdapter.onAddPicClickListener onAddPicClickListener = new CommitsAdapter.onAddPicClickListener() { @Override public void onAddPicClick() { show(); } }; //选择相册dialog private void show() { final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle); View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_item, null); //相册 Button bt_camera = inflate.findViewById(R.id.bt_camera); //取消 Button bt_cancel = inflate.findViewById(R.id.bt_cancel); dialog.setContentView(inflate); Window dialogWindow = dialog.getWindow(); dialogWindow.setGravity(Gravity.BOTTOM); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.y = 20; dialogWindow.setAttributes(lp); bt_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); bt_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); if (ContextCompat.checkSelfPermission(CommitsActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(CommitsActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1); } else { //从相册获取图片 openAlbum(); } } }); dialog.show(); } //进入相册 private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO);//打开相册 } //相册权限申请 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(this, "你拒绝了权限申请,可能无法打开相册哟", Toast.LENGTH_SHORT).show(); } break; default: } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CHOOSE_PHOTO: if (resultCode == RESULT_OK) { // 判断手机系统版本号 if (Build.VERSION.SDK_INT >= 19) { // 4.4及以上系统使用这个方法处理图片 handleImageOnKitKat(data); } else { // 4.4以下系统使用这个方法处理图片 handleImageBeforeKitKat(data); } } break; default: break; } } private void handleImageOnKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(this, uri)) { // 如果是document类型的Uri,则通过document id处理 String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; // 解析出数字格式的id String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri. getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { // 如果是content类型的Uri,则使用普通方式处理 imagePath = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { // 如果是file类型的Uri,直接获取图片路径即可 imagePath = uri.getPath(); } displayImage(imagePath); // 根据图片路径显示图片 } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection) { String path = null; // 通过Uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore. Images.Media.DATA)); } cursor.close(); } return path; } private void displayImage(String imagePath) { // Bitmap bitmap = BitmapFactory.decodeFile(imagePath); Bitmap bitmap1 = getBitmapFromUri(this, getImageContentUri(this, imagePath)); if (bitmap1 != null) { //获取图片 // File headFile = null; //把获取到的图片放进集合里 每次获取一个 selectList.add(new Image(bitmap1)); adapter.setList(selectList); adapter.notifyDataSetChanged(); } else { Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show(); } } // 通过uri加载图片 public static Bitmap getBitmapFromUri(Context context, Uri uri) { try { ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } catch (Exception e) { e.printStackTrace(); } return null; } public static Uri getImageContentUri(Context context, String path) { Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{path}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); return Uri.withAppendedPath(baseUri, "" + id); } else { // 如果图片不在手机的共享图片数据库,就先把它插入。 if (new File(path).exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, path); return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } //将bitmap转化为png格式 //首先获取了系统相册的地址,然后每次我拍下照片或者选择照片时, // 都进行简单的压缩,因为图片要上传到服务器进行审核管理,做成微信头像之类的超级压缩方法有损画质, // 所以我只是进行了简单的压缩上传最后写成一个文件。(在第二个页面的时候可能会有几个问题, // 三个ImageView即是三个bitmap,三个File文件。如何判断及正确的显示,我们可以定义成全局变量, // 因为都是点击事件,所以bitmap会在点击后修改,然后保存下来。 public File saveMyBitmap(Bitmap mBitmap, String prefix) { File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File file = null; try { file = File.createTempFile( prefix, /* prefix */ ".jpg" // , /* suffix */ // storageDir /* directory */ ); FileOutputStream fos = new FileOutputStream(file); //创建一个字节数组输出流对象 //Bitmap.CompressFormat format 图像的压缩格式; //int quality 图像压缩率,0-100。 0 压缩100%,100意味着不压缩; //OutputStream stream 写入压缩数据的输出流; mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);//通过bitmap中的compress,将图片压缩到os流对象中. //其中第二个参数quality,为100表示不压缩,如果为80,表示压缩百分之20. // Bitmap.createScaledBitmap(mBitmap, mBitmap.getWidth()/2, mBitmap.getHeight()/2, true); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } return file; } @Override public void onClick(View view) { int id = view.getId(); //提交 if (id == R.id.bt_put) { //获取问题描述 input = et_input.getText().toString(); //获取手机号等 phone = et_phone.getText().toString(); if (TextUtils.isEmpty(input) || input.length() < 10) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("反馈内容10-300字之间"); builder.setNegativeButton(("OK"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else { //这里把图片上传给后台,后台返回图片地址(建议上传图片给后台之前,图片做压缩处理) if (selectList.size() == 0) { getData(""); } else { upphoto(selectList); } } } else if (id == R.id.iv_back) { finish(); } } //上传图片 private void upphoto(final List<Image> filePaths) { mWeiboDialog = WeiboDialogUtils.createLoadingDialog(CommitsActivity.this, "加载中..."); //开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { try { //1 . 拿到OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // MediaType.parse() 里面是上传的文件类型。 MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (int i = 0; i < filePaths.size(); i++) { Image image = filePaths.get(i); //把bitmap转为数组 File headFile = saveMyBitmap(image.getPhoto(), "head"); File mFiles[] = new File[]{headFile}; //创建RequestBody封装参数 RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), mFiles[i]); // 参数分别为, 请求key ,文件名称 , RequestBody builder.addFormDataPart("zyFile", mFiles[i].getName(), fileBody); } MultipartBody requestBody = builder.build(); // 3 . 构建Request,将FormBody作为Post方法的参数传入 Request request = new Request.Builder() .url("http://172.28.60.97:8200/ZYGameServer_v2/v1/upload/feedback") .post(requestBody) .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); getfeedback(responseData); } catch (IOException e) { e.printStackTrace(); } } //一个JSON对象——JSONObject{} //一个JSON数组——JSONArray[] private void getfeedback(String responseData) { try { // Log.i("zyag", responseData); //借用线程来为传图片加加载动画 具体思路当图片上传成功后调用 handler.sendEmptyMessageDelayed(2, 0); JSONObject jsonObject1 = new JSONObject(responseData); String path = jsonObject1.getString("path"); getData(path); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } private void getData(String strPath) { mWeiboDialog = WeiboDialogUtils.createLoadingDialog(CommitsActivity.this, "加载中..."); //开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { try { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); JSONObject json = new JSONObject(); try { json.put("zyno", FeedbackGlobalManager.getInstanse().getZykey()); json.put("userId", ZyagUtils.getAndroidID(CommitsActivity.this)); json.put("model", ZyagUtils.getDeviceModle()); json.put("osVersion", ZyagUtils.getAndroidSystemVersionName()); json.put("language", ZyagUtils.getLanguage()); json.put("network", ZyagUtils.GetNetype(CommitsActivity.this)); json.put("appVersion", ZyagUtils.getPackageVersion(CommitsActivity.this)); json.put("content", input); json.put("des", phone); // System.out.println("CommitsActivity.getData strPath=" + strPath); if (!TextUtils.isEmpty(strPath)) { json.put("imgs", strPath);//图片地址url } } catch (JSONException e) { e.printStackTrace(); } //1 . 拿到OkHttpClient对象 OkHttpClient client = new OkHttpClient(); //创建一个RequestBody(参数1:数据类型 参数2传递的json串) RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json)); //3 . 构建Request,将FormBody作为Post方法的参数传入 Request request = new Request.Builder() .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/feedback") .post(requestBody) .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); getfeedback(responseData); } catch (IOException e) { e.printStackTrace(); } } private void getfeedback(String responseData) { try { JSONObject jsonObject = new JSONObject(responseData); String code = jsonObject.getString("code"); if ("0".equals(code)) { FeedbackGlobalManager.getInstanse().getFeedback().onSucess(); handler.sendEmptyMessageDelayed(2, 0); } else { FeedbackGlobalManager.getInstanse().getFeedback().onFailure(); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }

 

recyclerview 适配器
package com.example.zyghfeedback.commits; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.zyghfeedback.R; import com.example.zyghfeedback.assist.Image; import java.util.ArrayList; import java.util.List; public class CommitsAdapter extends RecyclerView.Adapter<CommitsAdapter.ViewHolder> { //用于判断是否显示图标 //有图片 public static final int TYPE_CAMERA = 1; //没有图片 public static final int TYPE_PICTURE = 2; private List<Image> list = new ArrayList<>(); private LayoutInflater mInflater; private Context context; private int selectMax = 4; /** * 点击添加图片跳转 */ private onAddPicClickListener mOnAddPicClickListener; public interface onAddPicClickListener { void onAddPicClick(); } //获取最大显示个数 public void setSelectMax(int selectMax) { this.selectMax = selectMax; } //获取图片集合 public void setList(List<Image> list) { this.list = list; } public CommitsAdapter(Context context, onAddPicClickListener mOnAddPicClickListener) { this.context = context; mInflater = LayoutInflater.from(context); this.mOnAddPicClickListener = mOnAddPicClickListener; } /** * 创建ViewHolder */ @NonNull @Override public CommitsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = mInflater.inflate(R.layout.photo_item, viewGroup, false); final ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull CommitsAdapter.ViewHolder viewHolder, int position) { //少于selectMax张,显示继续添加的图标 if (getItemViewType(position) == TYPE_CAMERA) { //显示添加图片图标 viewHolder.mImg.setImageResource(R.mipmap.group); viewHolder.mImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOnAddPicClickListener.onAddPicClick(); } }); viewHolder.ll_del.setVisibility(View.INVISIBLE); } else { //显示删除图片图标 viewHolder.ll_del.setVisibility(View.VISIBLE); //删除图标点击事件 viewHolder.ll_del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int index = viewHolder.getAdapterPosition(); // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码, // 通过源码分析应该是bindViewHolder()暂未绘制完成导致,知道原因的也可联系我~感谢 if (index != RecyclerView.NO_POSITION) { list.remove(index); notifyItemRemoved(index); notifyItemRangeChanged(index, list.size()); } } }); Image image = list.get(position); //显示选中的图片 viewHolder.mImg.setImageBitmap(image.getPhoto()); //itemView 的点击事件 if (mItemClickListener != null) { viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int adapterPosition = viewHolder.getAdapterPosition(); mItemClickListener.onItemClick(adapterPosition, v); } }); } } } @Override public int getItemCount() { //判断存储图片个数和最大个数 if (list.size() < selectMax) { return list.size() + 1; } else { return list.size(); } } //形式:条件表达式 ?程序块1 :程序块2 ; //含义:如果条件表达式为真,则本程序语句执行程序块1,程序块1的值即为整个表达式的值, 否则为表达式2的值。 private boolean isShowAddItem(int position) { int size = list.size() == 0 ? 0 : list.size(); return position == size; } @Override public int getItemViewType(int position) { if (isShowAddItem(position)) { //有图片 return TYPE_CAMERA; } else { //没有图片 return TYPE_PICTURE; } } public class ViewHolder extends RecyclerView.ViewHolder { ImageView mImg; LinearLayout ll_del; ImageView iv_duration; public ViewHolder(@NonNull View view) { super(view); mImg = (ImageView) view.findViewById(R.id.fiv); ll_del = (LinearLayout) view.findViewById(R.id.ll_del); iv_duration = (ImageView) view.findViewById(R.id.iv_duration); } } //点击事件接口 protected OnItemClickListener mItemClickListener; public interface OnItemClickListener { void onItemClick(int position, View v); } public void setOnItemClickListener(OnItemClickListener listener) { this.mItemClickListener = listener; } }

  

存放图片工具类
package com.example.zyghfeedback.assist; import android.graphics.Bitmap; public class Image { private Bitmap photo; public Image(Bitmap photo) { this.photo = photo; } public Bitmap getPhoto() { return photo; } public void setPhoto(Bitmap photo) { this.photo = photo; } }

  

 

$flag 上一页 下一页

上一篇:组件间数据交互

下一篇:hive