Android 多图上传后将图片进行九宫格展示的实例代码
不多说上代码
public abstract class NineGridAdapter { protected Context context; protected List list; public NineGridAdapter(Context context, List list) { this.context = context; this.list = list; } public abstract int getCount(); public abstract String getUrl(int positopn); public abstract Object getItem(int position); public abstract long getItemId(int position); public abstract View getView(int i, View view); }
package com.wd.weidologin.pic; import android.content.Context; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class NineGridlayout extends ViewGroup { private NineGridAdapter adapter; private OnItemClickListerner onItemClickListerner; // 行间距 private int lineSpace; //列间距 private int gap; private final int DEFAULT_WIDTH = 140; private int columns;// private int rows;// private int totalWidth; private Context context; int singleWidth = 0, singleHeight = 0; private int defaultWidth, defaultHeight; private int oldCount; public NineGridlayout(Context context) { this(context, null); } public NineGridlayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public NineGridlayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; gap = dip2px(context, 10); lineSpace = dip2px(context,10); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); defaultWidth = defaultHeight = dip2px(context, DEFAULT_WIDTH); } public void setDefaultWidth(int defaultWidth) { this.defaultWidth = defaultWidth; } public void setDefaultHeight(int defaultHeight) { this.defaultHeight = defaultHeight; } public void setAdapter(NineGridAdapter adapter) { this.adapter = adapter; if (adapter == null) { return; } //初始化布局形状 generateChildrenLayout(adapter.getCount()); //这里做一个重用view的处理 // if (oldCount == 0) { removeAllViews(); for (int i = 0; i < adapter.getCount(); i++) { View itemView = adapter.getView(i, null); addView(itemView, generateDefaultLayoutParams()); } // } /*else { //以前添加过view int newViewCount = adapter.getCount(); if (oldCount > newViewCount) { removeViews(newViewCount - 1, oldCount - newViewCount); for (int i = 0; i < newViewCount - 1; i++) { adapter.getView(i, getChildAt(i)); } } else if (oldCount < newViewCount) { for (int i = 0; i < newViewCount - oldCount; i++) { View itemView = adapter.getView(i, null); addView(itemView, generateDefaultLayoutParams()); } } }*/ oldCount = adapter.getCount(); requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); totalWidth = sizeWidth - getPaddingLeft() - getPaddingRight(); if (adapter != null && adapter.getCount() > 0) { int measureWidth, measureHeight; int childrenCount = adapter.getCount(); if (childrenCount == 1) { singleWidth = defaultWidth; singleHeight = defaultHeight; } else { singleWidth = (totalWidth - gap * (3 - 1)) / 3; singleHeight = singleWidth; } measureChildren(MeasureSpec.makeMeasureSpec(singleWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(singleHeight, MeasureSpec.EXACTLY)); measureWidth = singleWidth * columns + gap * (columns - 1); measureHeight = singleHeight * rows + lineSpace * (rows - 1); setMeasuredDimension(sizeWidth, measureHeight); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { layoutChildrenView(); } private void layoutChildrenView() { if (adapter == null || adapter.getCount() == 0) { return; } int childrenCount = adapter.getCount(); for (int i = 0; i < childrenCount; i++) { int[] position = findPosition(i); int left = (singleWidth + gap) * position[1] + getPaddingLeft(); int top = (singleHeight + lineSpace) * position[0] + getPaddingTop(); int right = left + singleWidth; int bottom = top + singleHeight; ImageView childrenView = (ImageView) getChildAt(i); if (childrenCount == 1) { //只有一张图片 childrenView.setScaleType(ImageView.ScaleType.FIT_CENTER); } else { childrenView.setScaleType(ImageView.ScaleType.CENTER_CROP); } final int itemPosition = i; childrenView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (onItemClickListerner != null) { onItemClickListerner.onItemClick(v, itemPosition); } } }); childrenView.layout(left, top, right, bottom); } } private int[] findPosition(int childNum) { int[] position = new int[2]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if ((i * columns + j) == childNum) { position[0] = i;//行 position[1] = j;//列 break; } } } return position; } public int getGap() { return gap; } public void setGap(int gap) { this.gap = gap; } /** * 根据图片个数确定行列数量 * 对应关系如下 * num row column * 1 1 1 * 2 1 2 * 3 1 3 * 4 2 2 * 5 2 3 * 6 2 3 * 7 3 3 * 8 3 3 * 9 3 3 * * @param length */ private void generateChildrenLayout(int length) { if (length <= 3) { rows = 1; columns = length; } else if (length <= 6) { rows = 2; columns = 3; if (length == 4) { columns = 2; } } else { rows = 3; columns = 3; } } /** * dp to px */ public static int dip2px(Context context, double dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public void setOnItemClickListerner(OnItemClickListerner onItemClickListerner) { this.onItemClickListerner = onItemClickListerner; } public interface OnItemClickListerner { public void onItemClick(View view, int position); } }
package com.wd.weidologin.home; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.wd.weidologin.R; import com.wd.weidologin.adapter.AttentionRequestAdapter; import com.wd.weidologin.okutil.okRE; import com.wd.weidologin.pic.NineGridAdapter; import com.wd.weidologin.pic.NineGridlayout; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity2 extends AppCompatActivity { private RecyclerView ry; private AttentionRequestAdapter attentionRequestAdapter; private ArrayList<CircleBean.ResultEntity> lists=new ArrayList<>(); private NineGridlayout mGV; private CircleBean.ResultEntity result; private String picture; private List<String> list = new ArrayList<String>(); private Adapter adapter; public static final String ACTION ="com.example.casts"; private String msg; private SharedPreferences canfig; private SharedPreferences.Editor edited; private String imageUrl = "http://pic1.nipic.com/2008-09-08/200898163242920_2.jpg";//如果没有接口可以用这个简单代替这个就不需要进行切割了 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); init();//(有接口的情况) list.add(imageUrl);//没有接口的情况 ---==================== if (adapter == null){ adapter = new Adapter(this,list); mGV.setAdapter(adapter); } mGV.setOnItemClickListerner(new NineGridlayout.OnItemClickListerner() { @Override public void onItemClick(View view, int position) { Toast.makeText(getApplicationContext(), String.valueOf(position),Toast.LENGTH_LONG).show(); } });//没有接口的情况 ---====================不要混 } private void init() { // int sickCircleId = getIntent().getIntExtra("sickCircleId", 0); canfig = getSharedPreferences("canfig", Context.MODE_PRIVATE); edited = canfig.edit(); int resultkey = canfig.getInt("resultkey", 0); String url="http:....."+resultkey; HashMap<String, String> headmap = new HashMap<>(); headmap.put("userId","287"); headmap.put("sessionId","1604985492394287"); okRE.getInstance().getCircledetails(url,headmap, new okRE.NetCallBack() { @Override public void onSuccess(String string) { CircleBean circleBean = new Gson().fromJson(string, CircleBean.class); picture = circleBean.getResult().getPicture(); Toast.makeText(MainActivity2.this, picture+"", Toast.LENGTH_SHORT).show(); mGV = findViewById(R.id.d); String[] split = picture.split(",");//一般多图上传后需要将图片进行切割 if (picture.equals("")){//在这里我进行了是否有图片的判断以免没有图片还进行占位 mGV.setVisibility(View.GONE); } for (int i = 0; i < split.length; i++) { list.add(split[i]); } if (adapter == null){ adapter = new Adapter(MainActivity2.this,list); mGV.setAdapter(adapter); } mGV.setOnItemClickListerner(new NineGridlayout.OnItemClickListerner() {图片点击事件 @Override public void onItemClick(View view, int position) { Toast.makeText(getApplicationContext(), String.valueOf(position),Toast.LENGTH_LONG).show(); } }); } @Override public void onFail(String string) { // Toast.makeText(MainActivity.this, string+"", Toast.LENGTH_SHORT).show(); } }); } private class Adapter extends NineGridAdapter {//适配器 public Adapter(Context context, List list){ super(context,list); } @Override public int getCount() { return list == null?0:list.size(); } @Override public String getUrl(int positon) { return getItem(positon) == null ? null : getItem(positon).toString(); } @Override public Object getItem(int position) { return (list == null) ? null : list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int i, View view) { ImageView imageView = new ImageView(getApplicationContext()); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setBackgroundColor(Color.parseColor("#f5f5f5")); imageView.setLayoutParams(lp); Glide.with(context).load(getUrl(i)).into(imageView); return imageView; } } }
最后因为这个包含网络请求所以需要进行设置
在res下创建xml文件夹创建network_security_config.xml
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
放到
并且添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
网路请求请看以往博客 多图上传请看以往博客或者我上传的代码,后续我会将全部整合上传demo
感谢观看
到此这篇关于Android 多图上传后将图片进行九宫格展示的文章就介绍到这了,更多相关Android 多图展示九宫格内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)