zoukankan      html  css  js  c++  java
  • Android View 上下左右四种间距的设置方法

    RecyclerView控件大家肯定不陌生,已经应用有一段时间了,最近在项目中写一个GridLayout样式的RecyclerView时需要设置,item之间左右的间距,下面是我总结的一个设置间距的方法分享给大家。

    下面是没间距的情况

     

    想要设置item之间的间距需要自己创建一个继承自RecyclerView.ItemDecoration的类

    public class RecyclerViewSpacesItemDecoration extends RecyclerView.ItemDecoration {
    
       private HashMap<String, Integer> mSpaceValueMap;
    
       public static final String TOP_DECORATION = "top_decoration";
       public static final String BOTTOM_DECORATION = "bottom_decoration";
       public static final String LEFT_DECORATION = "left_decoration";
       public static final String RIGHT_DECORATION = "right_decoration";
    ​
       public RecyclerViewSpacesItemDecoration(HashMap<String, Integer> mSpaceValueMap) {
           this.mSpaceValueMap = mSpaceValueMap;
       }
    ​
       @Override
       public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
           if (mSpaceValueMap.get(TOP_DECORATION) != null)
               outRect.top = mSpaceValueMap.get(TOP_DECORATION);
           if (mSpaceValueMap.get(LEFT_DECORATION) != null)
    
               outRect.left = mSpaceValueMap.get(LEFT_DECORATION);
           if (mSpaceValueMap.get(RIGHT_DECORATION) != null)
               outRect.right = mSpaceValueMap.get(RIGHT_DECORATION);
           if (mSpaceValueMap.get(BOTTOM_DECORATION) != null)
    
               outRect.bottom = mSpaceValueMap.get(BOTTOM_DECORATION);
    
       }
    
    }
    下面是 设置RecyclerView间距的关键方法
    HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
    stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION,50);//top间距
    
    stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION,100);//底部间距
    
    stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.LEFT_DECORATION,50);//左间距
    
    stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION,100);//右间距
    
    mRecyclerView.addItemDecoration(newRecyclerViewSpacesItemDecoration(stringIntegerHashMap));

    可以根据自己的实际情况去设置想要的间距,也可以去单独设置
    下面是设置间距后的效果图

  • 相关阅读:
    GoldenGate 19.1实时文本文件加载攻略
    windows 10 excel 打开超连接提示 组织策略阻止...
    验证ogg同步数据库表无主键表且目标表包含隐藏字段
    配置ogg从Oracle到PostgreSQL的同步复制json数据
    pi
    GoldenGate 19.1 发布
    ogg同步DDL时,源和目标端表空间名称不同的解决思路
    总目录索引(开发精华总结)
    Spring Cloud Nacos分布式配置中心
    Spring Cloud Nacos&Feign负载均衡
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/7436580.html
Copyright © 2011-2022 走看看