码迷,mamicode.com
首页 > 移动开发 > 详细

Android 实现朋友圈有图片和视频

时间:2018-07-20 16:49:37      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:record   nbsp   加载   wip   attr   oid   phi   wrap   sbt   

最近开发比较烦,这个作为我第一篇博客吧。

技术分享图片

效果就是图上的样子。

首先是布局文件,没什么就是一个RecycleView 
<android.support.v7.widget.RecyclerView 
android:id="@+id/dis_rv" 
android:layout_width="match_parent" 
android:layout_height="wrap_content"> 
</android.support.v7.widget.RecyclerView>
 
然后是item的布局文件,item布局文件是一个cardview。我这个比较乱,因为有圆角图片作为头像,有标题,有内容,然后是一个自定义九宫格的控件,下面是个ImageView作为视频的封面,开始都让他们隐藏,在适配器里判断,让对应的显示出来。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_marginBottom="15dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="5dp"
    app:cardUseCompatPadding="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <cn.com.jwtimes.www.jwtimes.view.RoundImageView
            android:layout_width="54dp"
            android:layout_height="54dp"
            android:layout_marginLeft="12dp"
            android:layout_marginTop="10dp"
            android:src="@mipmap/touxiang" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/dis_disname_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                android:paddingTop="10dp"
                android:text="前合租华安"
                android:textColor="#000"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/dis_conrent_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:paddingRight="10dp"
                android:text="冯绍峰的上升到发送的范德萨范德萨范德萨"
                android:textColor="#666"
                android:textSize="13sp" />

            <cn.com.jwtimes.www.jwtimes.view.NineGridTestLayout xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/layout_nine_grid"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_marginTop="8dp"
                app:sapcing="4dp" />


            <FrameLayout
                android:id="@+id/frameLayout"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_marginRight="40dp"
                android:visibility="gone">

                <ImageView
                    android:id="@+id/pic_iiv"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:background="@color/datadetailtext"
                    android:scaleType="fitXY" />

                <ImageView
                    android:id="@+id/start_iv"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_gravity="center"
                    android:src="@mipmap/startvoi" />
            </FrameLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/dis_time_tv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="2015-08-02 13:31"
                        android:textColor="#AFAFAF"
                        android:textSize="10sp" />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="6dp"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@mipmap/upload_location" />

                        <TextView
                            android:id="@+id/dis_pos_tv"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginBottom="12dp"
                            android:layout_marginLeft="5dp"
                            android:text="北京市丰台"
                            android:textColor="#AFAFAF"
                            android:textSize="10sp" />
                    </LinearLayout>

                </LinearLayout>

                <ImageButton
                    android:id="@+id/ibm_delect"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_marginRight="13dp"
                    android:layout_marginTop="4dp"
                    android:background="@null"
                    android:src="@mipmap/upload_more" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

下面我们来看适配器 我适配器更乱 。我先把整体代码贴出来.

package cn.com.jwtimes.www.jwtimes.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.jwtimes.www.jwtimes.R;
import cn.com.jwtimes.www.jwtimes.bean.DisasterUpload;
import cn.com.jwtimes.www.jwtimes.fragment.UploadFragment;
import cn.com.jwtimes.www.jwtimes.ui.disaupload.PlayMovieActivity;
import cn.com.jwtimes.www.jwtimes.view.NineGridTestLayout;


/**
 * Created by 王超然 on 2016/6/6.
 */
public class RecycleDisAdapter extends RecyclerView.Adapter<RecycleDisAdapter.ViewHolder> {

    private List<DisasterUpload.DataEntity.ListEntity> datas;
    private LayoutInflater inflater;
    private List<String> imageList;
    UploadFragment fm;
    Bitmap bitmap;

    public RecycleDisAdapter(List<DisasterUpload.DataEntity.ListEntity> datas, Context mContext, List<String> imageList, UploadFragment fm) {
        this.datas = datas;
        this.imageList = imageList;
        this.fm = fm;
        this.inflater = LayoutInflater.from(mContext);
    }

    public void setList(List<DisasterUpload.DataEntity.ListEntity> list) {
        datas = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {


        View convertView = inflater.inflate(R.layout.disaster_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(convertView);
        return viewHolder;


    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.setIsRecyclable(false);
        holder.dis_disname_tv.setText(datas.get(position).getSbName());
        holder.dis_conrent_tv.setText(datas.get(position).getSbContent());
        holder.dis_pos_tv.setText(datas.get(position).getLocation());
        holder.dis_time_tv.setText(datas.get(position).getSbTime());
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        holder.pic_iv.setImageBitmap((Bitmap) msg.obj);
                        break;
                }
                super.handleMessage(msg);
            }
        };
        if (datas.get(position).getSpList().size() != 0) {
            holder.frameLayout.setVisibility(View.VISIBLE);
            final String file = "http://124.193.178.222:1888/JwsdApp/" + datas.get(position).getSpList().get(0).getSpURL();
            Map<Integer, Bitmap> bitmapMap = new HashMap<>();
            if (bitmapMap.containsKey(position)) {
                 bitmap = bitmapMap.get(position);
                holder.pic_iv.setImageBitmap(bitmap);
            } else {
                Thread t = new Thread(new Runnable(){
                    public void run(){
                        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                        //获取网络视频
                        try {
                            retriever.setDataSource(file, new HashMap<String, String>());
                            bitmap = retriever.getFrameAtTime();
                            if (bitmap!=null){
                                Message message = handler.obtainMessage();
                                message.what = 1;
                                message.obj = bitmap;
                                handler.sendMessage(message);

                            }

                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (RuntimeException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                retriever.release();
                            } catch (RuntimeException e) {
                                e.printStackTrace();
                            }
                        }
                    }});
                t.start();

            }
            holder.start_iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(fm.getActivity(), PlayMovieActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("text", file);
                    intent.putExtras(bundle);
                    fm.getActivity().startActivity(intent);
                }
            });

        }

            imageList.clear();
            for (int i = 0; i < datas.get(position).getTpList().size(); i++) {
                imageList.add("http://124.193.178.222:1888/JwsdApp/" + datas.get(position).getTpList().get(i).getTpURL());
            }

            holder.layout.setUrlList(imageList);



    }

    @Override
    public int getItemCount() {
        return getListSize(datas);
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        private NineGridTestLayout layout;
        private TextView dis_disname_tv, dis_conrent_tv, dis_pos_tv, dis_time_tv;
        private ImageButton ibm_delect;
        private FrameLayout frameLayout;
        private ImageView pic_iv, start_iv;

        ViewHolder(View itemView) {
            super(itemView);
            frameLayout = (FrameLayout) itemView.findViewById(R.id.frameLayout);
            dis_disname_tv = (TextView) itemView.findViewById(R.id.dis_disname_tv);
            dis_conrent_tv = (TextView) itemView.findViewById(R.id.dis_conrent_tv);
            dis_pos_tv = (TextView) itemView.findViewById(R.id.dis_pos_tv);
            dis_time_tv = (TextView) itemView.findViewById(R.id.dis_time_tv);
            pic_iv = (ImageView) itemView.findViewById(R.id.pic_iiv);
            layout = (NineGridTestLayout) itemView.findViewById(R.id.layout_nine_grid);
            start_iv = (ImageView) itemView.findViewById(R.id.start_iv);
            ibm_delect = (ImageButton) itemView.findViewById(R.id.ibm_delect);
            ibm_delect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    fm.showdelectPopwindow();
                    fm.backgroundAlpha(0.5f);
                }
            });
        }
    }

    private int getListSize(List<DisasterUpload.DataEntity.ListEntity> list) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        return list.size();
    }
    public void addAll(List<DisasterUpload.DataEntity.ListEntity> dd) {
        datas.addAll(dd);
        notifyDataSetChanged();

    }

    public void clear() {
        datas.clear();
        imageList.clear();
        notifyDataSetChanged();
    }
}

其余的也没什么好说的 我主要说说设置封面经历,我要获取网络视频的第一帧作为相册封面,开始写完特别卡,因为每次都要请求,我就想我建一个bitmap的集合把图片存里,然后用position作为key每次我都去我的集合里找一遍,有就从集合取,没有就请求,然后发现还是卡,后来我想那干脆开个线程让她加载,然后发现,加载完以后, 我在切换别的fragment都是空白的 ,后来发现我没写handler通知更新UI。

首先 后台返回的数据有两个集合一个是图片集合一个是视频集合,但视频只有一个所以我判断了视频集合不等于0的时候显示ImageView。

if (datas.get(position).getSpList().size() != 0) {
            holder.frameLayout.setVisibility(View.VISIBLE);
            final String file = "http://124.193.178.222:1888/JwsdApp/" + datas.get(position).getSpList().get(0).getSpURL();
            Map<Integer, Bitmap> bitmapMap = new HashMap<>();//bitmap的集合
            if (bitmapMap.containsKey(position)) {
                 bitmap = bitmapMap.get(position);
                holder.pic_iv.setImageBitmap(bitmap);//集合要是存在就设置上
            } else {
                Thread t = new Thread(new Runnable(){
                    public void run(){//开启线程获取视频第一帧
                        MediaMetadataRetriever retriever = new MediaMetadataRetriever(); //获取网络视频
                        try {
                            retriever.setDataSource(file, new HashMap<String, String>());
                            bitmap = retriever.getFrameAtTime();
                            if (bitmap!=null){
                                Message message = handler.obtainMessage();//用handler发送通知
                                message.what = 1;
                                message.obj = bitmap;
                                handler.sendMessage(message);

                            }

                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (RuntimeException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                retriever.release();
                            } catch (RuntimeException e) {
                                e.printStackTrace();
                            }
                        }
                    }});
                t.start();

            }

然后点击视频要能播放 所以我把点击事件写在了这里:

 holder.start_iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(fm.getActivity(), PlayMovieActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("text", file);
                    intent.putExtras(bundle);
                    fm.getActivity().startActivity(intent);
                }
            });

然后下面是这设置图片的九宫格控件

            imageList.clear();
            for (int i = 0; i < datas.get(position).getTpList().size(); i++) {
                imageList.add("http://124.193.178.222:1888/JwsdApp/" + datas.get(position).getTpList().get(i).getTpURL());
            }
            holder.layout.setUrlList(imageList);

NineGridLayout的代码

package cn.com.jwtimes.www.jwtimes.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import cn.com.jwtimes.www.jwtimes.R;

/**
 * Created by 王超然 on 2016/6/6.
 */
public abstract class NineGridLayout extends ViewGroup {

    private static final float DEFUALT_SPACING = 3f;
    private static final int MAX_COUNT = 9;

    protected Context mContext;
    private float mSpacing = DEFUALT_SPACING;
    private int mColumns;
    private int mRows;
    private int mTotalWidth;
    private int mSingleWidth;

    private boolean mIsShowAll = false;
    private boolean mIsFirst = true;
    private ArrayList<String> mUrlList = new ArrayList<>();

    public NineGridLayout(Context context) {
        super(context);
        init(context);
    }

    public NineGridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NineGridLayout);

        mSpacing = typedArray.getDimension(R.styleable.NineGridLayout_sapcing, DEFUALT_SPACING);
        typedArray.recycle();
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        if (getListSize(mUrlList) == 0) {
            setVisibility(GONE);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        mTotalWidth = right - left;
        mSingleWidth = (int) ((mTotalWidth - mSpacing * (3 - 1)) / 3);
        if (mIsFirst) {
            notifyDataSetChanged();
            mIsFirst = false;
        }
    }

    /**
     * 设置间隔
     *
     * @param spacing
     */
    public void setSpacing(float spacing) {
        mSpacing = spacing;
    }

    /**
     * 设置是否显示所有图片(超过最大数时)
     *
     * @param isShowAll
     */
    public void setIsShowAll(boolean isShowAll) {
        mIsShowAll = isShowAll;
    }

    public void setUrlList(List<String> urlList) {
        if (getListSize(urlList) == 0) {
            setVisibility(GONE);
            return;
        }
        setVisibility(VISIBLE);

        mUrlList.clear();
        mUrlList.addAll(urlList);

        if (!mIsFirst) {
            notifyDataSetChanged();
        }
    }

    public void notifyDataSetChanged() {
        post(new TimerTask() {
            @Override
            public void run() {
                refresh();
            }
        });
    }

    private void refresh() {
        removeAllViews();
        int size = getListSize(mUrlList);
        if (size > 0) {
            setVisibility(VISIBLE);
        } else {
            setVisibility(GONE);
        }

        if (size == 1) {
            String url = mUrlList.get(0);
            RatioImageView imageView = createImageView(0, url);

            //避免在ListView中一张图未加载成功时,布局高度受其他item影响
            LayoutParams params = getLayoutParams();
            params.height = mSingleWidth;
            setLayoutParams(params);
            imageView.layout(0, 0, mSingleWidth, mSingleWidth);

            boolean isShowDefualt = displayOneImage(imageView, url, mTotalWidth);
            if (isShowDefualt) {
                layoutImageView(imageView, 0, url, false);
            } else {
                addView(imageView);
            }
            return;
        }

        generateChildrenLayout(size);
        layoutParams();

        for (int i = 0; i < size; i++) {
            String url = mUrlList.get(i);
            RatioImageView imageView;
            if (!mIsShowAll) {
                if (i < MAX_COUNT - 1) {
                    imageView = createImageView(i, url);
                    layoutImageView(imageView, i, url, false);
                } else { //第9张时
                    if (size <= MAX_COUNT) {//刚好第9张
                        imageView = createImageView(i, url);
                        layoutImageView(imageView, i, url, false);
                    } else {//超过9张
                        imageView = createImageView(i, url);
                        layoutImageView(imageView, i, url, true);
                        break;
                    }
                }
            } else {
                imageView = createImageView(i, url);
                layoutImageView(imageView, i, url, false);
            }
        }
    }

    private void layoutParams() {
        int singleHeight = mSingleWidth;

        //根据子view数量确定高度
        LayoutParams params = getLayoutParams();
        params.height = (int) (singleHeight * mRows + mSpacing * (mRows - 1));
        setLayoutParams(params);
    }

    private RatioImageView createImageView(final int i, final String url) {
        RatioImageView imageView = new RatioImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickImage(i, url, mUrlList);
            }
        });
        return imageView;
    }

    /**
     * @param imageView
     * @param url
     * @param showNumFlag 是否在最大值的图片上显示还有未显示的图片张数
     */
    private void layoutImageView(RatioImageView imageView, int i, String url, boolean showNumFlag) {
        final int singleWidth = (int) ((mTotalWidth - mSpacing * (3 - 1)) / 3);
        int singleHeight = singleWidth;

        int[] position = findPosition(i);
        int left = (int) ((singleWidth + mSpacing) * position[1]);
        int top = (int) ((singleHeight + mSpacing) * position[0]);
        int right = left + singleWidth;
        int bottom = top + singleHeight;

        imageView.layout(left, top, right, bottom);

        addView(imageView);
        if (showNumFlag) {//添加超过最大显示数量的文本
            int overCount = getListSize(mUrlList) - MAX_COUNT;
            if (overCount > 0) {
                float textSize = 30;
                final TextView textView = new TextView(mContext);
                textView.setText("+" + String.valueOf(overCount));
                textView.setTextColor(Color.WHITE);
                textView.setPadding(0, singleHeight / 2 - getFontHeight(textSize), 0, 0);
                textView.setTextSize(textSize);
                textView.setGravity(Gravity.CENTER);
                textView.setBackgroundColor(Color.BLACK);
                textView.getBackground().setAlpha(120);

                textView.layout(left, top, right, bottom);
                addView(textView);
            }
        }
        displayImage(imageView, url);
    }

    private int[] findPosition(int childNum) {
        int[] position = new int[2];
        for (int i = 0; i < mRows; i++) {
            for (int j = 0; j < mColumns; j++) {
                if ((i * mColumns + j) == childNum) {
                    position[0] = i;//
                    position[1] = j;//
                    break;
                }
            }
        }
        return position;
    }

    /**
     * 根据图片个数确定行列数量
     *
     * @param length
     */
    private void generateChildrenLayout(int length) {
        if (length <= 3) {
            mRows = 1;
            mColumns = length;
        } else if (length <= 6) {
            mRows = 2;
            mColumns = 3;
            if (length == 4) {
                mColumns = 2;
            }
        } else {
            mColumns = 3;
            if (mIsShowAll) {
                mRows = length / 3;
                int b = length % 3;
                if (b > 0) {
                    mRows++;
                }
            } else {
                mRows = 3;
            }
        }

    }

    protected void setOneImageLayoutParams(RatioImageView imageView, int width, int height) {
        imageView.setLayoutParams(new LayoutParams(width, height));
        imageView.layout(0, 0, width, height);

        LayoutParams params = getLayoutParams();
//        params.width = width;
        params.height = height;
        setLayoutParams(params);
    }

    private int getListSize(List<String> list) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        return list.size();
    }

    private int getFontHeight(float fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.ascent);
    }

    /**
     * @param imageView
     * @param url
     * @param parentWidth 父控件宽度
     * @return true 代表按照九宫格默认大小显示,false 代表按照自定义宽高显示
     */
    protected abstract boolean displayOneImage(RatioImageView imageView, String url, int parentWidth);

    protected abstract void displayImage(RatioImageView imageView, String url);

    protected abstract void onClickImage(int position, String url, ArrayList<String> urlList);
}

NineGridTestLayout的代码

package cn.com.jwtimes.www.jwtimes.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;

import cn.com.jwtimes.www.jwtimes.ui.disaupload.ImageViewActivity;
import cn.com.jwtimes.www.jwtimes.utils.ImageLoaderUtil;


/**
 * Created by 王超然 on 2016/6/6.
 */
public class NineGridTestLayout extends NineGridLayout {

    protected static final int MAX_W_H_RATIO = 3;
    private Context context;

    public NineGridTestLayout(Context context) {
        super(context);
    }

    public NineGridTestLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected boolean displayOneImage(final RatioImageView imageView, String url, final int parentWidth) {

        ImageLoaderUtil.displayImage(mContext, imageView, url, ImageLoaderUtil.getPhotoImageOption(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
                int w = bitmap.getWidth();
                int h = bitmap.getHeight();

                int newW;
                int newH;
                if (h > w * MAX_W_H_RATIO) {//h:w = 5:3
                    newW = parentWidth / 2;
                    newH = newW * 5 / 3;
                } else if (h < w) {//h:w = 2:3
                    newW = parentWidth * 2 / 3;
                    newH = newW * 2 / 3;
                } else {//newH:h = newW :w
                    newW = parentWidth / 2;
                    newH = h * newW / w;
                }
                setOneImageLayoutParams(imageView, newW, newH);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
        return false;
    }

    @Override
    protected void displayImage(RatioImageView imageView, String url) {
        ImageLoaderUtil.getImageLoader(mContext).displayImage(url, imageView, ImageLoaderUtil.getPhotoImageOption());
    }

    @Override
    protected void onClickImage(int i, String url, ArrayList<String> urlList) {

        Intent intent = new Intent(mContext, ImageViewActivity.class);
        intent.putExtra("picurl",url);

        mContext.startActivity(intent);
       // Toast.makeText(mContext, "点击了图片" + url, Toast.LENGTH_SHORT).show();
    }
}

然后就是fragment了 这里也没什么好说的。我用了SwipyRefreshLayout作为下拉刷新和上拉加载,我这里面有两个popupwindow 一个是这个fragment的Activity传的拍摄button,一个是item的删除button。

package cn.com.jwtimes.www.jwtimes.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mingle.widget.LoadingView;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;

import java.util.ArrayList;
import java.util.List;

import cn.com.jwtimes.www.jwtimes.JWtimes;
import cn.com.jwtimes.www.jwtimes.R;
import cn.com.jwtimes.www.jwtimes.adapter.RecycleDisAdapter;
import cn.com.jwtimes.www.jwtimes.bean.DisasterUpload;
import cn.com.jwtimes.www.jwtimes.ui.disaupload.MovieRecorderActivity;
import cn.com.jwtimes.www.jwtimes.ui.disaupload.UploadphotoActivity;
import cn.com.jwtimes.www.jwtimes.uri.Uris;

/**
 * Created by 王超然 on 2016/9/7.
 */
public class UploadFragment extends BaseFragmet implements View.OnClickListener {
    private Context mContext;
    private ImageButton iv_show_pop;
    private PopupWindow mPopWindow;
    private LoadingView loadingView;
    private RecyclerView disUp_rv;
    private RecyclerView.LayoutManager mLayoutManager;
    private RecycleDisAdapter adapter;
    private List<DisasterUpload.DataEntity.ListEntity> datas;
    private List<DisasterUpload.DataEntity> dates;
    private int ap009 = 1;
    private int ap0010;
    private DisasterUpload disasterUpload;
    private List<String> imageList;
    private SwipyRefreshLayout zxyj_swipyrefreshlayout;
    private int position;
    private static final String ARG_LIST = "list";


    @SuppressLint("ValidFragment")
    public UploadFragment(Context context, ImageButton iv_camera) {
        this.mContext = context;
        this.iv_show_pop = iv_camera;
    }

    public UploadFragment() {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_upload, null);
        initView(view);
        loadData();
        disUp_rv.setAdapter(adapter);
        zxyj_swipyrefreshlayout = (SwipyRefreshLayout) view.findViewById(R.id.zxyj_swipyrefreshlayout);
        zxyj_swipyrefreshlayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction == SwipyRefreshLayoutDirection.TOP) {
                    position = 0;
                    adapter.clear();
                    loadData();
                    zxyj_swipyrefreshlayout.setRefreshing(false);
                } else if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
                    loadMoreData();
                    zxyj_swipyrefreshlayout.setRefreshing(false);
                    // Toast.makeText(getActivity(), "暂时还没开发", Toast.LENGTH_SHORT).show();
                    zxyj_swipyrefreshlayout.setRefreshing(false);
                }

            }
        });
        iv_show_pop.setOnClickListener(this);
        return view;
    }

    private void loadMoreData() {
        SharedPreferences share = getActivity().getSharedPreferences("userInfo", Activity.MODE_WORLD_READABLE);
        String userName = share.getString("USER_NAME", "");
        String passWord = share.getString("PASSWORD", "");
        TelephonyManager telephonyMgr = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        String ap003 = telephonyMgr.getDeviceId();
        String ap006 = share.getString("ap006", "");
        int ap007 = share.getInt("ap007", 0);
        int num = Integer.parseInt(dates.get(0).getNumber());
        ap009++;
        ap0010 = 5;
        if ((num + ap0010) / ap009 < ap0010) {
            Toast.makeText(getActivity(), "没有更多数据.......", Toast.LENGTH_SHORT).show();
        } else {

            String resUrl = Uris.URI_DSUP +
                    "ap001=" + userName + "&ap002=" + passWord + "&ap003=" + ap003 + "&ap006=" + ap006 + "&ap007=" + ap007 + "&ap009=" + ap009 + "&ap0010=" + ap0010;
            Log.i("resUrl", resUrl);
            //实例化请求队列
            StringRequest request = new StringRequest(Request.Method.POST,
                    String.format(resUrl),
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Gson gson = new Gson();
                            disasterUpload = gson.fromJson(response, DisasterUpload.class);
                            loadingView.setVisibility(View.GONE);
                            datas.addAll(disasterUpload.getData().getList());
                            adapter.addAll(disasterUpload.getData().getList());
                        }

                    },
                    null
            );

            //设置请求取消标记
            request.setTag("jjjjj");
            //将请求添加在请求队列
            JWtimes.getInstance().getQueue().add(request);

        }


    }

    private void initView(View view) {
        mLayoutManager = new LinearLayoutManager(getActivity());
        disUp_rv = (RecyclerView) view.findViewById(R.id.dis_rv);
        disUp_rv.setLayoutManager(mLayoutManager);
        imageList = new ArrayList<String>();
        loadingView = (LoadingView) view.findViewById(R.id.loadView);
        imageList.clear();
        adapter = new RecycleDisAdapter(new ArrayList<DisasterUpload.DataEntity.ListEntity>(), getActivity(), imageList, this);
        datas = new ArrayList<DisasterUpload.DataEntity.ListEntity>();
        dates = new ArrayList<DisasterUpload.DataEntity>();
    }


    private void loadData() {
        SharedPreferences share = getActivity().getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
        String userName = share.getString("USER_NAME", "");
        final String passWord = share.getString("PASSWORD", "");
        TelephonyManager telephonyMgr = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        String ap003 = telephonyMgr.getDeviceId();
        String ap006 = share.getString("ap006", "");
        int ap007 = share.getInt("ap007", 0);
        String resUrl = Uris.URI_DSUP + "ap001=" + userName + "&ap002=" + passWord + "&ap003=" + ap003 + "&ap006=" + ap006 + "&ap007=" + ap007 + "&ap009=1&ap0010=5";
        //实例化请求队列


        StringRequest request = new StringRequest(Request.Method.POST,
                String.format(resUrl),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        disasterUpload = gson.fromJson(response, DisasterUpload.class);
                        loadingView.setVisibility(View.GONE);
                        datas.addAll(disasterUpload.getData().getList());
                        adapter.addAll(disasterUpload.getData().getList());
                        dates.add(disasterUpload.getData());

                    }

                },
                null
        );


        request.setTag("ppp");
        //将请求添加在请求队列
        JWtimes.getInstance().getQueue().add(request);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.photo_ibm:
                showPopupWindow();
                backgroundAlpha(0.5f);
                break;
        }
    }

    /**
     * 显示选择window
     */
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_photo, null);
        mPopWindow = new PopupWindow(contentView,
                RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        //   mPopWindow.setOutsideTouchable(true);
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        //设置各个控件的点击响应
        TextView tv1 = (TextView) contentView.findViewById(R.id.photo_tv);
        TextView tv2 = (TextView) contentView.findViewById(R.id.vdio_tv);
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(mContext, UploadphotoActivity.class);
                startActivityForResult(intent1, 11);
                getActivity().overridePendingTransition(R.anim.anim_slide_right_in, R.anim.anim_slide_left_out);
                mPopWindow.dismiss();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MovieRecorderActivity.class);
                startActivityForResult(intent, 12);
                getActivity().overridePendingTransition(R.anim.anim_slide_right_in, R.anim.anim_slide_left_out);
                mPopWindow.dismiss();
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(mContext).inflate(R.layout.activity_home_pager, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);

    }

    /**
     * 删除的popupWindow
     */
    public void showdelectPopwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_delect, null);
        mPopWindow = new PopupWindow(contentView,
                RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        //设置各个控件的点击响应
        TextView delect_tv = (TextView) contentView.findViewById(R.id.delect_tv);

        delect_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mPopWindow.dismiss();
            }
        });

        //显示PopupWindow
        View rootview = LayoutInflater.from(mContext).inflate(R.layout.activity_home_pager, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        adapter.clear();
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 11 && data != null) {
            position = 0;
            adapter.clear();
            loadData();
            return;
        } else if (requestCode == 12 && data != null) {
            position = 0;
            adapter.clear();
            loadData();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

我是Android小渣渣,代码写的一团乱麻。demo是没有的因为项目比较大,没有单独奥,不过哪里缺什么文件,都可以找我。 
compile ‘com.android.support:cardview-v7:23.2.0’ 
compile files(‘libs/universal-image-loader-1.9.5.jar’)图片加载的imageloader 
compile ‘com.github.orangegangsters:swipy:1.2.2@aar’ 

Android 实现朋友圈有图片和视频

标签:record   nbsp   加载   wip   attr   oid   phi   wrap   sbt   

原文地址:https://www.cnblogs.com/zhujiabin/p/9341997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!