Android RecyclerView的item大小保持四個半

 

如今有這麼一個需求,實現下圖的UI。  我想你應該能想到用RecyclerView實現, 當我唰唰唰幾分鐘作完以後,UI設計師跟我說,每一個item,不管在什麼手機上,都要顯示四個半,具體看下圖。html

 

咱們都知道,Android手機的屏幕大小不一,這種需求咱們不可能把圖片的寬寫死,或者寫成wrap_content,這個時候就要在java代碼中從新測量而且從新設置寬了。代碼以下:java

 

  1.  
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) ((getResources().getDisplayMetrics().widthPixels - CommonUtil.dip2px(mContext, 5)) / 4.5f),
  2.  
    ViewGroup.LayoutParams.MATCH_PARENT);

這裏-5是由於 個人RecyclerView在佈局中marginLeft了5dp,若是你沒有設置margin值,則不用減去。佈局

dip2px代碼:post

  1.  
    /**
  2.  
    * 根據手機分辨率從dp轉成px
  3.  
    *
  4.  
    * @param context
  5.  
    * @param dpValue
  6.  
    * @return
  7.  
    */
  8.  
    public static int dip2px(Context context, float dpValue) {
  9.  
    final float scale = context.getResources().getDisplayMetrics().density;
  10.  
    return (int) (dpValue * scale + 0.5f);
  11.  
    }

 

解釋一下思路:建立出LayoutParams 第一個參數是寬,第二個是高, 寬度使用getResources方法獲取屏幕的寬度,再減去5的和, 除以4.5。高度仍是match_parent。spa

 

而後把params設置給item便可設計

 

mLL_collect.setLayoutParams(params);

 

這個時候每一個item繪製時,都會從新測量屏幕寬度,就能實現任何屏幕都是四個半的需求,3個半 5個半也是同理,把4.5換成3.五、5.5便可。code

相關文章
相關標籤/搜索