现在在Android应用中,GridView中每个Item都是正方形的场景越来越常见。比如 陌陌 的搜索结果界面

陌陌的搜索界面显示

Android手机和IPhone不同, IPhone硬件是苹果自己出的,屏幕尺寸基本没啥太大差别,所以很好适配。

而Android就不一样了,中高低档手机都有,屏幕尺寸严重不统一,如何做到一种实现适配各种Android手机屏幕才是关键。

今天我们就来研究下具体实现方式。

由于Android本身对设备特性支持比较有好,所以实现起来还是非常简单滴!

问题分析

要实现这种正方形布局,所以宽度不能是固定值,不然就要根据不同的屏幕尺寸分别设置了,麻烦死了。

比较好的方式就是设置一个最小宽度,然后多余的空间每个单元格平均分配,这个GridView本身就支持。

在测试的布局文件activity_main.xml 中代码如下:

Java

< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

>

< GridView

android:id="@+id/grid"

android:background="@color/grid_bg_color"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:columnWidth=" @dimen/itemSize "

android:gravity="center"

android:horizontalSpacing="4dp"

android:verticalSpacing="4dp"

android:numColumns=" auto_fit "

android:scrollbars="vertical"

android:scrollbarStyle="insideOverlay"

android:stretchMode=" columnWidth "

/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

android:layout_width="match_parent"

android:layout_height="match_parent"

>

android:id="@+id/grid"

android:background="@color/grid_bg_color"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:columnWidth=" @dimen/itemSize "

android:gravity="center"

android:horizontalSpacing="4dp"

android:verticalSpacing="4dp"

android:numColumns=" auto_fit "

android:scrollbars="vertical"

android:scrollbarStyle="insideOverlay"

android:stretchMode=" columnWidth "

/>

注意上面标记为蓝色的属性取值。这样在计算GridView的列数时,先根据宽度看看能放几列,然后把多余的空间平均分配到每列中。 这样列数和宽度的问题就解决了。

在默认情况下itemSize的取值为100dp.

在每个GridItem宽度解决的情况下,只要保证高度和宽度一样就OK了。 使用一个自定义View,在onMeasure函数中设置下即可。

示例中选择一个自定义的Layout,代码如下:

Java

package org.goodev.squaregrid;

import android.content.Context;

import android.util.AttributeSet;

import android.widget.RelativeLayout;

public class SquareLayout extends RelativeLayout {

public SquareLayout(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

public SquareLayout(Context context, AttributeSet attrs) {

super(context, attrs);

}

public SquareLayout(Context context) {

super(context);

}

@SuppressWarnings("unused")

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

// For simple implementation, or internal size is always 0.

// We depend on the container to specify the layout size of

// our view. We can't really know what it is since we will be

// adding and removing different arbitrary views and do not

// want the layout to change as this happens.

setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));

// Children are just made to fill our space.

int childWidthSize = getMeasuredWidth();

int childHeightSize = getMeasuredHeight();

//高度和宽度一样

heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

packageorg.goodev.squaregrid;

importandroid.content.Context;

importandroid.util.AttributeSet;

importandroid.widget.RelativeLayout;

publicclassSquareLayoutextendsRelativeLayout{

publicSquareLayout(Contextcontext,AttributeSetattrs,intdefStyle){

super(context,attrs,defStyle);

}

publicSquareLayout(Contextcontext,AttributeSetattrs){

super(context,attrs);

}

publicSquareLayout(Contextcontext){

super(context);

}

@SuppressWarnings("unused")

@Override

protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){

// For simple implementation, or internal size is always 0.

// We depend on the container to specify the layout size of

// our view. We can't really know what it is since we will be

// adding and removing different arbitrary views and do not

// want the layout to change as this happens.

setMeasuredDimension(getDefaultSize(0,widthMeasureSpec),getDefaultSize(0,heightMeasureSpec));

// Children are just made to fill our space.

intchildWidthSize=getMeasuredWidth();

intchildHeightSize=getMeasuredHeight();

//高度和宽度一样

heightMeasureSpec=widthMeasureSpec=MeasureSpec.makeMeasureSpec(childWidthSize,MeasureSpec.EXACTLY);

super.onMeasure(widthMeasureSpec,heightMeasureSpec);

}

}

然后在GridItem布局文件 item.xml中使用上面的自定义layout:

Java

< org.goodev.squaregrid.SquareLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="wrap_content"

>

< ImageView

android:id="@+id/icon"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="fitXY"

android:src="@drawable/ic_launcher" />

android:id="@+id/text"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#88000000"

android:textColor="#FFFFFF"

android:layout_alignParentBottom="true"

android:gravity="center_horizontal"

/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

android:layout_width="match_parent"

android:layout_height="wrap_content"

>

android:id="@+id/icon"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="fitXY"

android:src="@drawable/ic_launcher"/>

android:id="@+id/text"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#88000000"

android:textColor="#FFFFFF"

android:layout_alignParentBottom="true"

android:gravity="center_horizontal"

/>

上面的测试布局中,用了两个控件,一个方形的ImageView显示图标,一个TextView在图标上显示一个半透明的文本。

然后自定义一个Adapter来使用上面的布局即可。GridAdapter.java 代码如下

Java

package org.goodev.squaregrid;

import java.util.ArrayList;

import java.util.List;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;

public class GridAdapter extends BaseAdapter{

public static class Item{

public String text;

public int resId;

}

private List mItems = new ArrayList();

private Context mContext;

public GridAdapter(Context context) {

//测试数据

for (int i = 0; i < 50; i++) {

Item object = new Item();

object.text = "Text "+i;

object.resId = R.drawable.icon;

mItems.add(object);

}

mContext = context;

}

@Override

public int getCount() {

return mItems.size();

}

@Override

public Object getItem(int position) {

return mItems.get(position);

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

if(convertView == null) {

convertView = LayoutInflater.from(mContext).inflate(R.layout.item, null);

}

ImageView image = (ImageView) convertView.findViewById(R.id.icon);

TextView text = (TextView) convertView.findViewById(R.id.text);

Item item = (Item) getItem(position);

image.setImageResource(item.resId);

text.setText(item.text);

return convertView;

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

packageorg.goodev.squaregrid;

importjava.util.ArrayList;

importjava.util.List;

importandroid.content.Context;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.BaseAdapter;

importandroid.widget.ImageView;

importandroid.widget.TextView;

publicclassGridAdapterextendsBaseAdapter{

publicstaticclassItem{

publicStringtext;

publicintresId;

}

privateListmItems=newArrayList();

privateContextmContext;

publicGridAdapter(Contextcontext){

//测试数据

for(inti=0;i<50;i++){

Itemobject=newItem();

object.text="Text "+i;

object.resId=R.drawable.icon;

mItems.add(object);

}

mContext=context;

}

@Override

publicintgetCount(){

returnmItems.size();

}

@Override

publicObjectgetItem(intposition){

returnmItems.get(position);

}

@Override

publiclonggetItemId(intposition){

returnposition;

}

@Override

publicViewgetView(intposition,ViewconvertView,ViewGroupparent){

if(convertView==null){

convertView=LayoutInflater.from(mContext).inflate(R.layout.item,null);

}

ImageViewimage=(ImageView)convertView.findViewById(R.id.icon);

TextViewtext=(TextView)convertView.findViewById(R.id.text);

Itemitem=(Item)getItem(position);

image.setImageResource(item.resId);

text.setText(item.text);

returnconvertView;

}

}

最后在 MainActivity.java 中把上面的Adapter设置到GridView中即可。

Java

package org.goodev.squaregrid;

import android.os.Bundle;

import android.app.Activity;

import android.widget.GridView;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

GridView view = (GridView) findViewById(R.id.grid);

view.setAdapter(new GridAdapter(getBaseContext()));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

packageorg.goodev.squaregrid;

importandroid.os.Bundle;

importandroid.app.Activity;

importandroid.widget.GridView;

publicclassMainActivityextendsActivity{

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

GridViewview=(GridView)findViewById(R.id.grid);

view.setAdapter(newGridAdapter(getBaseContext()));

}

}

下面是在手机上运行的截图

SquareGridView测试截图

下面是在Nexus 7平板上的截图:

测试程序在Nexus 7上的截图

可以看到上面的效果虽然也是正方形,但是在大屏幕下显示100dp的方块是否看起来太小了。 把该尺寸在平板上修改大点是非常容易的。只需要在 values-sw600dp 目录中(Nexus 7 的最小屏幕宽度为600dp)创建一个文件

dimens.xml 内容如下:

Java

< resources>

< dimen name="itemSize">140dp

1

2

3

140dp

这样当程序在Nexus 7上运行的时候,会根据140dp来计算列数。最终效果如下:

在Nexus 7上改进后的布局

同样的,如果想在手机横屏(比如Galaxy Nexus手机)下也显示大一点的图,则可以根据手机的长度的dp值分别设置一个区间

比如Galaxy Nexus手机屏幕高度为640dp,但是在横屏情况下应用能用的宽度只有570dp,另外的70dp位于右侧的系统功能键(返回键、Home键、最近任务键)占用了。所以创建个目录

values-w570dp-land,在里面设置ItemWidth即可, dimens.xml 内容:

Java

&lt ;resources>

< dimen name="itemSize">140dp

1

2

3

<resources>

140dp

下面两个图是横屏的对比

Galaxy Nexus 横屏显示小图标

Galaxy Nexus 横屏显示修改后的图标

现在效果已经完成了,只差没有选中按下状态的标示了。 要实现这个Press状态,可在item.xml中添加一个View,当Press的时候 显示一个半透明的图层来标示。

修改后的item.xml 代码如下

Java

< org.goodev.squaregrid.SquareLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="wrap_content"

>

< ImageView

android:id="@+id/icon"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="fitXY"

android:src="@drawable/ic_launcher" />

android:id="@+id/text"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#88000000"

android:textColor="#FFFFFF"

android:layout_alignParentBottom="true"

android:gravity="center_horizontal"

/>

android:id="@+id/press"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/item_press_bg"

/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

android:layout_width="match_parent"

android:layout_height="wrap_content"

>

android:id="@+id/icon"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="fitXY"

android:src="@drawable/ic_launcher"/>

android:id="@+id/text"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#88000000"

android:textColor="#FFFFFF"

android:layout_alignParentBottom="true"

android:gravity="center_horizontal"

/>

android:id="@+id/press"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/item_press_bg"

/>

上面红色部分的View只设置的一个背景,在选中或者按下的状态下显示一个半透明度颜色。

效果如下:

第二行中间那个按下效果

android中自适应布局教程,Android实现自适应正方形GridView相关推荐

  1. Android中相对布局是,Android之相对布局

    Android中的布局分为六种,分别是相对布局.线性布局.表格布局.网格布局.帧布局.绝对布局,良好的布局设计对UI界面至关重要,下面先来看看先相对布局. 相对布局(RelativeLayout): ...

  2. android中自适应布局教程,Android自适应布局设计技巧

    由于目前在做的一款app需要适配手机和平板,所以我在研究怎么构建可适应所有屏幕尺寸的布局方法. 在web的自适应布局上我有很多经验,比如使用网格流,CSS3中的media queries属性等等,这些 ...

  3. android中帧布局效果,Android开发实现布局帧布局霓虹灯效果示例

    本文实例讲述了android开发实现布局帧布局霓虹灯效果.分享给大家供大家参考,具体如下: 效果图: 实现方式: framelayout中,设置8个textview,在主函数中,设计颜色数组,通过有序 ...

  4. android linearlayout属性大全,Android中LinearLayout布局的常用属性总结读书笔记

    8种机械键盘轴体对比 本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选? 原CSDN博客已弃用,文章会逐渐迁移过来. 应朋友们反馈的Android基础薄弱的问题,决定出一套Android基础教程 ...

  5. android怎么查看方法被谁调用,Android中查看布局文件中的控件(view,id)在哪里被调用(使用)...

    在阅读别人的代码时通常是很痛苦的,有时很想要看一看布局中的控件在哪里被调用了,为之很苦恼 在这里提供一种方法. 复制要查看的控件ID,到R文件中搜索到该ID, 接下来就好办的了,选中ID按下Ctrl鼠 ...

  6. Android中常见布局

    android中常见布局 [1]线性布局 水平 垂直. <?xml version="1.0" encoding="utf-8"?> <Lin ...

  7. iOS 11 自适应布局教程: 开始

    原文:Adaptive Layout Tutorial in iOS 11: Getting Started 作者:József Vesza 译者:kmyhy 更新说明:本教程由 József Ves ...

  8. android布局添加布局,Android中添加布局和初始化布局总结

    在android中布局很重要,下面总结下布局的三种形式 ①.在Activity的onCreate()方法中进行添加比如:setContentView(R.layout.activity_main); ...

  9. 速读原著-Android应用开发入门教程(Android中建立工程)

    2.4 Android中建立工程 2.4.1. 建立工程 Android 的 SDK 环境安装完成后,就可以在 SDK 中建立工程并进行调试了. 建立 Android 工程步骤如下: 选择" ...

最新文章

  1. 率清华团队研发“天机芯”登《Nature》封面,他说类脑计算是发展人工通用智能的基石...
  2. 高频交易都有哪些著名的算法
  3. Linux下基于socket多线程并发通信的实现
  4. python 创建目录_Python虚拟环境的搭建与使用
  5. html圆角边框只有左边,border-radius以外的CSS圆角边框制作方法
  6. java冒泡排序找最大的值_(13)數組操作:遍歷、輸出最大值、冒泡排序、選擇排序,java已有的排序方法、折半查找...
  7. 中考计算机IE操作题,信息技术中考历年真题集锦(IE操作)
  8. DOM-3 【utils/待讲评】节点属性、方法、封装方法、DOM结构
  9. java手机网站开发工具_制作网站常用的网页开发工具有哪些
  10. 这才是厉害程序员的标配!
  11. 安装IPython攻略
  12. Fuschia 是什么样的一个操作系统
  13. 如何查看Android项目的gradle版本和路径
  14. java exec 关闭,Java学习之使用Runtime.exec()启动、关闭Tomcat
  15. 最新O泡易支付系统源码-源码全解密,无后门,本地资源化
  16. Java 数组的三种创建方法
  17. C# 将错误日志写到txt文件
  18. Python数据分析pandas入门练习题(七)
  19. VBA 对 range() 或 cells() 的内容格式的修改, 如 range.address(0,0) cells().formulaR1C1
  20. 雨季车辆天窗漏水解决银弹

热门文章

  1. 在IntelliJ IDEA配置Tomcat
  2. 值传递与引用传递区别,具体表现
  3. 大理大学日常作业计算机基础知识,大理学院成人高等教育大学计算机基础课程作业.doc...
  4. linux emule 编译 wx-config --libs,Linux下的wxWidgets静态编译实现方法
  5. 代码流程图_助力理解js代码,进阶JavaScript代码能力——js2flowchart
  6. @propertysource 读不到properties_敢不敢来挑战,读对一班就是学霸
  7. php 动态引用dll文件路径,win平台环境变量与dll动态链接库搜索路径小结
  8. cookie helper.php,CookieHelper cook crud 工具类
  9. 《人月神话》——一部被名字误导的软件开发的书——第一次阅读
  10. 启动项目的时候报驱动错误: not support oracle driver 1.0