用recyclerview实现对话(通过接口实现)

老规矩首先先上布局

咱们先看效果

布局实现

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#ffffff"
    android:layout_height="match_parent">

    <include
        android:id="@+id/include"
        layout="@layout/title"></include>

    <RelativeLayout
        android:id="@+id/rl_input"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:paddingBottom="12dp">

        <TextView
            android:id="@+id/tv_send"
            android:layout_width="50dp"
            android:layout_height="35dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="25dp"
            android:background="@drawable/send_bg"
            android:gravity="center"
            android:text="发送"
            android:textColor="#ffffffff"
            android:textSize="13sp" />

        <ImageView
            android:id="@+id/iv_photo"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignTop="@id/tv_send"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="19dp"
            android:src="@mipmap/photo" />

        <EditText
            android:id="@+id/et_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_toLeftOf="@id/tv_send"
            android:layout_toRightOf="@+id/iv_photo"
            android:background="@drawable/et_bg"
            android:hint="点击输入回复内容"
            android:paddingLeft="5dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textColor="#ffa5a5a5"
            android:textSize="13sp" />
    </RelativeLayout>

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/srl_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/rl_input"
        android:layout_below="@id/include"
        app:srlEnableAutoLoadMore="false">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srlTextPulling="@string/down"
            app:srlTextRelease="@string/Release" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginRight="25dp"
            android:fadeScrollbars="false"
            android:nestedScrollingEnabled="false"
            android:scrollbars="none"
            android:visibility="visible" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>


</RelativeLayout>

 java代码

我觉得最主要就是这两句一个是刷新列表(获取到有新的数据就刷新)下一句是把数据添加到最下面一行

myDetailsAdapter.notifyDataSetChanged();
recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);

 

public class FeedbackDetails extends Activity {
    private View include;
    private ImageView iv_back, iv_photo;
    private RecyclerView recycler_view;
    private TextView tv_send;
    private EditText et_input;
    private MyDetailsAdapter myDetailsAdapter;
    public static RelativeLayout rl_input;
    //反馈信息序列号
    private String serialNumber;
    //信息工具类
    private List<MyFeedbackDetailsModel> myFeedbackDetailsModel = new ArrayList<>();
    //上一页传递数据
    long feedbackTime;
    String content;
    //图片1
    String img1;
    //图片1
    String img2;
    //图片1
    String img3;
    //是否已解决
    int state;
    //是否显示已解决 未解决
    boolean no;
    //线程传递数据
    private Message send_message;
    //页码
    private int pageNum = 1;
    //每页条数
    private int pageSize = 10;
    public static final int CHOOSE_PHOTO = 2;// 相册
    //下拉刷新
    private RefreshLayout srl_layout;
    //获取图片
    private File headFile = null;
    private Dialog mWeiboDialog;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 100) {
                myDetailsAdapter.notifyDataSetChanged();
                recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);
            } else if (msg.what == 2) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
//                AlertDialog.Builder builder = new AlertDialog.Builder(FeedbackDetails.this);
//                builder.setTitle("提交成功");
            }
            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 mConfiguration = this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = mConfiguration.orientation; //获取屏幕方向
        if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
            //横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制为竖屏
        } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
            //竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
        }*/
//横竖屏切换 Configuration cf = this.getResources().getConfiguration(); int ori = cf.orientation; if (ori == cf.ORIENTATION_LANDSCAPE) { setContentView(R.layout.feedback_details); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else if (ori == cf.ORIENTATION_PORTRAIT) { setContentView(R.layout.feedback_details); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏 } setInit(); setOnclick(); } private void setInit() {
//从前一页获取数据 Intent intent = getIntent(); serialNumber = intent.getStringExtra("serialNumber"); feedbackTime = intent.getLongExtra("feedbackTime", 0); content = intent.getStringExtra("content"); img1 = intent.getStringExtra("img1"); img2 = intent.getStringExtra("img2"); img3 = intent.getStringExtra("img3"); state = intent.getIntExtra("state", 0); srl_layout = findViewById(R.id.srl_layout); no = true; getdata(); include = findViewById(R.id.include); iv_back = include.findViewById(R.id.iv_back); tv_send = findViewById(R.id.tv_send); iv_photo = findViewById(R.id.iv_photo); et_input = findViewById(R.id.et_input); recycler_view = findViewById(R.id.recycler_view); rl_input = findViewById(R.id.rl_input); //设置布局管理器 LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recycler_view.setLayoutManager(mLayoutManager); myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(content, "0", "0", "3", null, feedbackTime, img1, img2, img3, null, 0,no)); } private void setOnclick() { //设置adapter myDetailsAdapter = new MyDetailsAdapter(myFeedbackDetailsModel, this); recycler_view.setAdapter(myDetailsAdapter); recycler_view.scrollToPosition(myDetailsAdapter.getItemCount() - 1);//此句为设置显示 //设置Item添加和移除的动画 recycler_view.setItemAnimator(new DefaultItemAnimator());
//刷新 srl_layout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { pageNum++; getdata(); myDetailsAdapter.notifyDataSetChanged(); refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败 } }); iv_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); tv_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //获取用户输入 String text = et_input.getText().toString(); //用户输入发送到网络上 setsend(text, null); //内容发送成功之后清空输入文本框 et_input.setText(""); } }); iv_photo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { show(); } }); myDetailsAdapter.setOnItemClickListener(new MyDetailsAdapter.OnItemClickListener() { @Override public void ontv_no(View v) { setsend("0", null); rl_input.setVisibility(View.GONE); } @Override public void ontv_yes(View v) { setsend("1", null); no = false; } }); } 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(FeedbackDetails.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(FeedbackDetails.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(Intent.ACTION_PICK, null); // intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // startActivityForResult(intent, CHOOSE_PHOTO); 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; } } @TargetApi(19) 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); // 根据图片路径显示图片 // mWeiboDialog = WeiboDialogUtils.createLoadingDialog(FeedbackDetails.this, "加载中..."); // handler.sendEmptyMessageDelayed(1, 2000); } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); // mWeiboDialog = WeiboDialogUtils.createLoadingDialog(FeedbackDetails.this, "加载中..."); // handler.sendEmptyMessageDelayed(1, 2000); } 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) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; // Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); Bitmap bitmap1 = getBitmapFromUri(this, getImageContentUri(this, imagePath)); if (bitmap1 != null) { headFile = saveMyBitmap(bitmap1, "head"); upphoto(headFile); } 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; } //发送消息请求 public void setsend(final String text, final String bitmap) { //开启线程来发起网络请求 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("serialNumber", serialNumber); //消息内容 if (text.isEmpty()) { json.put("message", bitmap); //消息类型(0:文本;1:图片;2:系统) json.put("type", "1"); } else if (text.equals("0")) { json.put("message", text); //消息类型(0:文本;1:图片;2:系统) json.put("type", "2"); } else if (text.equals("1")) { json.put("message", text); //消息类型(0:文本;1:图片;2:系统) json.put("type", "2"); } else { json.put("message", text); //消息类型(0:文本;1:图片;2:系统) json.put("type", "0"); } } 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/sendMessage") .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 { JSONObject jsonObject1 = new JSONObject(responseData); String code = jsonObject1.getString("code"); if (code.equals("0")) { myFeedbackDetailsModel.clear(); pageNum = 1; myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(content, "0", "0", "3", null, feedbackTime, img1, img2, img3, null, 0,no)); getdata(); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } //上传图片 private void upphoto(final File bitmap) { mWeiboDialog = WeiboDialogUtils.createLoadingDialog(FeedbackDetails.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); if (bitmap != null) { RequestBody body = RequestBody.create(MediaType.parse("image/*"), bitmap); // 参数分别为, 请求key ,文件名称 , RequestBody builder.addFormDataPart("zyFile", bitmap.getName(), body); } 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); JSONObject jsonObject1 = new JSONObject(responseData); String path = jsonObject1.getString("path"); setsend("", path); //借用线程来为传图片加加载动画 具体思路当图片上传成功后调用 handler.sendEmptyMessageDelayed(2, 0); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } //请求显示数据 private void getdata() { //开启线程来发起网络请求 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("serialNumber", serialNumber); json.put("pageNum", pageNum); json.put("pageSize", pageSize); } 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/getChatInfoByPage") .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("fk",responseData); JSONObject jsonObject1 = new JSONObject(responseData); JSONArray jsonArray = jsonObject1.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); //消息内容 String message = jsonObject.getString("message"); //消息类型(0:文本;1:图片;;2:系统) String type = jsonObject.getString("type"); //0:未读;1:已读 String read = jsonObject.getString("read"); //消息来源(0:用户;1:平台) String source = jsonObject.getString("source"); String isValid = jsonObject.getString("isValid"); // 创建时间 long createTime = jsonObject.getLong("createTime"); myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(message, type, read, source, isValid, createTime, null, null, null, serialNumber, state,no)); } send_message = Message.obtain(); send_message.what = 100; handler.sendMessage(send_message); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }

 适配器使用了加载多布局(左边一个 右边一个) 

public class MyDetailsAdapter extends RecyclerView.Adapter {
    private List<MyFeedbackDetailsModel> myFeedbackDetailsModels;
    //判断文字超出三行后显示还是隐藏
    private Boolean flag = true;
    //设置常量
    //平台
    private static final int LEFT = 1;
    //用户
    private static final int RIGHT = 0;
    //头部
    private static final int TITLE = 3;
    private LayoutInflater inflater;
    private Context mContext;
    public MyDetailsAdapter(List<MyFeedbackDetailsModel> myFeedbackDetailsModels, Context context) {
        this.myFeedbackDetailsModels = myFeedbackDetailsModels;
        mContext = context;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        RecyclerView.ViewHolder holder = getViewHolderByViewType(viewType);
        return holder;
    }

    //点击事件接口
    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void ontv_no(View v);
        void ontv_yes(View v);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }
    /**
     * 根据不同的position,设置不同的ViewType
     * position表示当前是第几个Item,通过position拿到当前的Item对象,然后判断这个item对象需要那种视图
     */
    @Override
    public int getItemViewType(int position) {
        if (myFeedbackDetailsModels.get(position).getSource().equals("1")) {
            return LEFT;
        } else if (myFeedbackDetailsModels.get(position).getSource().equals("0")) {
            return RIGHT;
        } else if (myFeedbackDetailsModels.get(position).getSource().equals("null")) {
            return RIGHT;
        } else if (myFeedbackDetailsModels.get(position).getSource().equals("3")) {
            return TITLE;
        }
        return 0;
    }

    private RecyclerView.ViewHolder getViewHolderByViewType(int viewType) {
        View left = View.inflate(mContext, R.layout.left_item, null);
        View right = View.inflate(mContext, R.layout.right_item, null);
        View title = View.inflate(mContext, R.layout.title_item, null);
        RecyclerView.ViewHolder holder = null;
        switch (viewType) {
            case LEFT:
                holder = new ViewHolderLeft(left);
                break;
            case RIGHT:
                holder = new ViewHolderRight(right);
                break;
            case TITLE:
                holder = new ViewHolderTitle(title);
                break;
        }
        return holder;
    }

    /**
     * 获取图标 bitmap
     *
     * @param context
     * Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)//android 10存储图片地址
     */
    public static synchronized Drawable getBitmap(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext()
                    .getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        Drawable d = packageManager.getApplicationIcon(applicationInfo); //xxx根据自己的情况获取drawable

//        Bitmap APKicon;
//        if(d instanceof BitmapDrawable) {
//            APKicon  = ((BitmapDrawable)d).getBitmap();
//        }else{
//            Bitmap bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(),d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
//            Canvas canvas = new Canvas(bitmap);
//            d.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
//            d.draw(canvas);
//            APKicon = bitmap;
//        }
//        BitmapDrawable bd = (BitmapDrawable) d;
//        Bitmap bm = bd.getBitmap();
        return d;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        // 绑定数据
        MyFeedbackDetailsModel myFeedbackModel = myFeedbackDetailsModels.get(position);
        if (holder instanceof ViewHolderLeft) {
            FeedbackDetails feedbackDetails = new FeedbackDetails();
            //是平台系统IsValid = 1有效 =0无效
            if (myFeedbackModel.getSource().equals("1") && myFeedbackModel.getType().equals("2") && myFeedbackModel.getIsValid().equals("1")) {
                //如果问题已解决那么就不显示
                if (myFeedbackModel.getState() == 1) {
                    //布局隐藏
                    feedbackDetails.rl_input.setVisibility(View.GONE);
                } else {
                    //布局显示
                    if (myFeedbackModel.isNo()){
                        ((ViewHolderLeft) holder).ll_solve.setVisibility(View.VISIBLE);
                    }else {
                        ((ViewHolderLeft) holder).ll_solve.setVisibility(View.GONE);
                    }

                    feedbackDetails.rl_input.setVisibility(View.GONE);
                    //点击未解决
                    if (mItemClickListener != null) {
                        ((ViewHolderLeft) holder).tv_no.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mItemClickListener.ontv_no(v);
                            }
                        });
                    }
                    //已解决
                    if (mItemClickListener != null) {
                        ((ViewHolderLeft) holder).tv_yes.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mItemClickListener.ontv_yes(v);
                            }
                        });
                    }
                }
            } else {
                //是平台的系统的 无效的
                ((ViewHolderLeft) holder).ll_solve.setVisibility(View.GONE);
                feedbackDetails.rl_input.setVisibility(View.VISIBLE);
            }

            //更换应用头像
            ((ViewHolderLeft) holder).iv_head.setImageDrawable(getBitmap(mContext));
//            ((ViewHolderLeft) holder).iv_head.setImageBitmap(getBitmap(mContext));
            if (myFeedbackModel.getType().equals("1")) {
                ((ViewHolderLeft) holder).tv_text.setVisibility(View.GONE);
                ((ViewHolderLeft) holder).iv_photo.setVisibility(View.VISIBLE);
                //应用框架显示网络图片
                Glide.with(mContext)
                        .load(myFeedbackModel.getMessage())
                        .into(((ViewHolderRight) holder).iv_photo);
                ((ViewHolderLeft) holder).tv_date.setText(getUserDate(myFeedbackModel.getCreateTime()));
                //放大图片
                ((ViewHolderLeft) holder).iv_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.getContext().startActivity(new Intent(view.getContext(), OtherActivity.class).putExtra("photo", myFeedbackModel.getMessage()),
                                // 注意这里的sharedView
                                // Content,View(动画作用view),String(和XML一样)
                                ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
                    }

                });
            } else {
                ((ViewHolderLeft) holder).tv_text.setText(myFeedbackModel.getMessage());
                ((ViewHolderLeft) holder).tv_date.setText(getUserDate(myFeedbackModel.getCreateTime()));
            }
        } else if (holder instanceof ViewHolderRight) {
            // 如果设置了回调,则设置点击事件
            String url = FeedbackGlobalManager.getInstanse().getHeadImageStr();

            if ((url == null || url == ""|| url.equals(null)||url.isEmpty())) {
                ((ViewHolderRight) holder).iv_head.setImageResource(R.mipmap.default_head);
//                ((ViewHolderRight) holder).iv_head.setImageResource(R.drawable.tianjiazhaopian);
                //headType =0 网络图片
            } else {
                if (url.startsWith("http")) {
                    //应用框架显示网络图片
                    Glide.with(mContext)
                            .load(url)
                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .into(((ViewHolderRight) holder).iv_head);
                    //本地图片
                } else{
                    Bitmap bitmap= getBitmapFromUri(mContext, getImageContentUri(mContext,url));
//                    Bitmap bitmap = BitmapFactory.decodeFile(url);
//                    ((ViewHolderRight) holder).iv_head.setImageBitmap(createCircleBitmap(bitmap));
                    ((ViewHolderRight) holder).iv_head.setImageBitmap(bitmap);
                }
            }

//            }
            if (myFeedbackModel.getType().equals("1")) {
                ((ViewHolderRight) holder).tv_text.setVisibility(View.GONE);
                ((ViewHolderRight) holder).iv_photo.setVisibility(View.VISIBLE);
                //应用框架显示网络图片
                //指定图片大小
//                RequestOptions options = new RequestOptions()
//                        .override(250, 250);
//                initphoto(myFeedbackModel.getMessage(),((ViewHolderRight) holder).iv_photo);

                Glide.with(mContext)
                        .load(myFeedbackModel.getMessage())
                        .into(((ViewHolderRight) holder).iv_photo);

                ((ViewHolderRight) holder).tv_date.setText(getUserDate(myFeedbackModel.getCreateTime()));
                ((ViewHolderRight) holder).iv_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.getContext().startActivity(new Intent(view.getContext(), OtherActivity.class).putExtra("photo", myFeedbackModel.getMessage()),
                                // 注意这里的sharedView
                                // Content,View(动画作用view),String(和XML一样)
                                ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
                    }

                });
            } else {
                ((ViewHolderRight) holder).tv_text.setVisibility(View.VISIBLE);
                ((ViewHolderRight) holder).iv_photo.setVisibility(View.GONE);
                ((ViewHolderRight) holder).tv_text.setText(myFeedbackModel.getMessage());
                ((ViewHolderRight) holder).tv_date.setText(getUserDate(myFeedbackModel.getCreateTime()));
            }
        } else if (holder instanceof ViewHolderTitle) {
            //文字显示超过三行隐藏 点击展开才显示
            ((ViewHolderTitle) holder).tv_text.setText(myFeedbackModel.getMessage());
            ((ViewHolderTitle) holder).tv_text.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (((ViewHolderTitle) holder).tv_text.getLineCount() >= 3) {
                        ((ViewHolderTitle) holder).iv_more.setVisibility(View.VISIBLE);
//                        ((ViewHolderTitle) holder).iv_more.setImageResource(R.mipmap.more_open);
                    } else {
                        ((ViewHolderTitle) holder).iv_more.setVisibility(View.GONE);
                    }
                }
            });
            ((ViewHolderTitle) holder).iv_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (flag) {
                        flag = false;
                        ((ViewHolderTitle) holder).iv_more.setImageResource(R.mipmap.more);
                        ((ViewHolderTitle) holder).tv_text.setEllipsize(null);//展开
                        ((ViewHolderTitle) holder).tv_text.setMaxLines(Integer.MAX_VALUE);//把TextView行数显示取消掉
                        ((ViewHolderTitle) holder).tv_text.setSingleLine(false);//这个方法是必须设置的,否则无法展开
                    } else {
                        flag = true;
                        ((ViewHolderTitle) holder).iv_more.setImageResource(R.mipmap.more_open);
                        ((ViewHolderTitle) holder).tv_text.setEllipsize(TextUtils.TruncateAt.END); // 收缩
                        ((ViewHolderTitle) holder).tv_text.setMaxLines(3);
                    }
                }
            });
            ((ViewHolderTitle) holder).tv_date.setText(getUserDate(myFeedbackModel.getCreateTime()));
            //判断是否有图片
            if (myFeedbackModel.getImg1().equals("null")) {
                ((ViewHolderTitle) holder).ll_img.setVisibility(View.GONE);
            } else {
                ((ViewHolderTitle) holder).ll_img.setVisibility(View.VISIBLE);
                //应用框架显示网络图片
                Glide.with(mContext)
                        .load(myFeedbackModel.getImg1())
                        .into(((ViewHolderTitle) holder).iv_img1);
                //放大图片
                ((ViewHolderTitle) holder).iv_img1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.getContext().startActivity(new Intent(view.getContext(), OtherActivity.class).putExtra("photo", myFeedbackModel.getImg1()),
                                // 注意这里的sharedView
                                // Content,View(动画作用view),String(和XML一样)
                                ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
                    }

                });
//            应用框架显示网络图片
                Glide.with(mContext)
                        .load(myFeedbackModel.getImg2())
                        .into(((ViewHolderTitle) holder).iv_img2);
                //放大图片
                ((ViewHolderTitle) holder).iv_img2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.getContext().startActivity(new Intent(view.getContext(), OtherActivity.class).putExtra("photo", myFeedbackModel.getImg2()),
                                // 注意这里的sharedView
                                // Content,View(动画作用view),String(和XML一样)
                                ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
                    }

                });
                //应用框架显示网络图片
                Glide.with(mContext)
                        .load(myFeedbackModel.getImg3())
                        .into(((ViewHolderTitle) holder).iv_img3);
                //放大图片
                ((ViewHolderTitle) holder).iv_img3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.getContext().startActivity(new Intent(view.getContext(), OtherActivity.class).putExtra("photo", myFeedbackModel.getImg3()),
                                // 注意这里的sharedView
                                // Content,View(动画作用view),String(和XML一样)
                                ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(), view, "sharedView").toBundle());
                    }

                });
            }

        }
    }
    // 通过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;
            }
        }
    }

//    private Bitmap createCircleBitmap(Bitmap resource)
//    {
//        //获取图片的宽度
//        int width = resource.getWidth();
//        Paint paint = new Paint();
//        //设置抗锯齿
//        paint.setAntiAlias(true);
//        //创建一个与原bitmap一样宽度的正方形bitmap
//        Bitmap circleBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
//        //以该bitmap为低创建一块画布
//        Canvas canvas = new Canvas(circleBitmap);
//        //以(width/2, width/2)为圆心,width/2为半径画一个圆
//        canvas.drawCircle(width/2, width/2, width/2, paint);
//
//        //设置画笔为取交集模式
//        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//        //裁剪图片
//        canvas.drawBitmap(resource, 0, 0, paint);
//
//        return circleBitmap;
//    }
    public static String getUserDate(long sformat) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = formatter.format(new Date(sformat));   // 时间戳转换成时间     (这里也是毫秒时间戳)
        return sd;
    }

    @Override
    public int getItemCount() {
        return myFeedbackDetailsModels == null ? 0 : myFeedbackDetailsModels.size();
    }

    private class ViewHolderLeft extends RecyclerView.ViewHolder {
        TextView tv_date, tv_text, tv_no, tv_yes;
        ImageView iv_head, iv_photo;
        LinearLayout ll_solve;

        public ViewHolderLeft(View itemView) {
            super(itemView);
            tv_date = itemView.findViewById(R.id.tv_date);
            tv_text = itemView.findViewById(R.id.tv_text);
            iv_head = itemView.findViewById(R.id.iv_head);
            iv_photo = itemView.findViewById(R.id.iv_photo);
            ll_solve = itemView.findViewById(R.id.ll_solve);

            tv_no = itemView.findViewById(R.id.tv_no);
            tv_yes = itemView.findViewById(R.id.tv_yes);

        }
    }

    private class ViewHolderRight extends RecyclerView.ViewHolder {
        TextView tv_date, tv_text;
        ImageView iv_head;
        ImageView iv_photo;

        public ViewHolderRight(View itemView) {
            super(itemView);
            tv_date = itemView.findViewById(R.id.tv_date);
            tv_text = itemView.findViewById(R.id.tv_text);
            iv_head = itemView.findViewById(R.id.iv_head);
            iv_photo = itemView.findViewById(R.id.iv_photo);
            iv_head = itemView.findViewById(R.id.iv_head);
        }
    }

    private class ViewHolderTitle extends RecyclerView.ViewHolder {
        TextView tv_date, tv_text;
        ImageView iv_head;
        ImageView iv_img1, iv_img2, iv_img3, iv_more;
        LinearLayout ll_img;

        public ViewHolderTitle(View itemView) {
            super(itemView);
            tv_date = itemView.findViewById(R.id.tv_date);
            tv_text = itemView.findViewById(R.id.tv_text);
            iv_head = itemView.findViewById(R.id.iv_head);
            //图片一
            iv_img1 = itemView.findViewById(R.id.iv_img1);
            //图片二
            iv_img2 = itemView.findViewById(R.id.iv_img2);
            //图片三
            iv_img3 = itemView.findViewById(R.id.iv_img3);
            //显示更多
            iv_more = itemView.findViewById(R.id.iv_more);
            //图片布局
            ll_img = itemView.findViewById(R.id.ll_img);
}

布局我就贴一个另一个和这个差不多

这个一样也需要一个工具类具体可以参照我的另一篇文章

可能写的不是很好但是我会慢慢努力使它变好

posted @ 2020-01-10 11:04  九块  阅读(380)  评论(0编辑  收藏  举报