안 드 로 이 드 다 중 그림 업로드 후 그림 을 구 궁 격 으로 보 여 주 는 인 스 턴 스 코드

코드

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 폴 더 만 들 기 networksecurity_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 를 통합 해서 올 리 겠 습 니 다.
시청 해 주 셔 서 감사합니다.
안 드 로 이 드 다 중 사진 을 올 린 후 구 궁 격 전시 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 안 드 로 이 드 다 중 그림 은 구 궁 격 내용 을 보 여 줍 니 다.우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기