`
dawuafang
  • 浏览: 1105911 次
文章分类
社区版块
存档分类
最新评论

Android实现自适应正方形GridView Read more: http://blog.chengyunfeng.com/?p=465#ixzz2id8EQPMq

 
阅读更多

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

陌陌的搜索界面显示

陌陌的搜索界面显示

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

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

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

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

问题分析

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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="<span style="color: #0000ff;">@dimen/itemSize</span>"
android:gravity="center"
android:horizontalSpacing="4dp"
android:verticalSpacing="4dp"
android:numColumns="<span style="color: #0000ff;">auto_fit</span>"
android:scrollbars="vertical"
android:scrollbarStyle="insideOverlay"
android:stretchMode="<span style="color: #0000ff;">columnWidth</span>"
/>
</RelativeLayout>

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

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

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

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

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
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);
}
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<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" />
<TextView
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"
/>
</org.goodev.squaregrid.SquareLayout>

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

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

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
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<Item> mItems = new ArrayList<GridAdapter.Item>();
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;
}
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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()));
}
}

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

SquareGridView测试截图

SquareGridView测试截图

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

测试程序在Nexus 7上的截图

测试程序在Nexus 7上的截图

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

dimens.xml 内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <dimen name="itemSize">140dp</dimen>
</resources>

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

在Nexus 7上改进后的布局

在Nexus 7上改进后的布局

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

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

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

1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="itemSize">140dp</dimen>
</resources>

下面两个图是横屏的对比

Galaxy Nexus 横屏显示小图标

Galaxy Nexus 横屏显示小图标

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

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

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

修改后的item.xml 代码如下

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
<?xml version="1.0" encoding="utf-8"?>
<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" />
<TextView
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"
/>
<span style="color: #ff0000;"> <View</span>
<span style="color: #ff0000;"> android:id="@+id/press"</span>
<span style="color: #ff0000;"> android:layout_width="match_parent"</span>
<span style="color: #ff0000;"> android:layout_height="match_parent"</span>
<span style="color: #ff0000;"> android:background="@drawable/item_press_bg"</span>
<span style="color: #ff0000;"> /></span>
</org.goodev.squaregrid.SquareLayout>

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

效果如下:

第二行中间那个按下效果

第二行中间那个按下效果

代码:https://github.com/goodev/SquareGridView/tree/master/SquareGrid



Read more:http://blog.chengyunfeng.com/?p=465#ixzz2id8OpZes
分享到:
评论

相关推荐

    基于LINQ的博客网站毕业设计

    基于LINQ的博客网站发布地址:http://LinqBlog.51aspnet.org 基于ASP.NET MVC的博客网站发布地址:http://MvcBlog.51aspnet.org 基于ASP.NET MVC的博客网站毕业设计:http://download.csdn.net/source/1644144 ...

    Android源码: 透明圆角Dialog

    本例知识点:Dialog透明,圆角,及GridView的简单用法。 &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; ...

    Android实验指导(1).doc

    id="@+id/EditText01" " "android:layout_width="fill_parent" " "android:layout_height="wrap_content" " "/&gt; " "&lt;ImageView android:id="@+id/ImageView01" " "android:layout_width="wrap_content" " "android:...

    DevExpress gridview下拉框repositoryItemComboBox的使用

    DevExpress gridview下拉框repositoryItemComboBox的使用https://jiankunking.blog.csdn.net/article/details/42129247?...

    我的学习心得gridview

    int pageCount; //总页面数 int curPageIndex = 1;//当前页面 ... GridView1.PageCount.ToString() : (GridView1.PageIndex + 2).ToString()); btnLast.CommandName =GridView1.PageCount.ToString();

    GridView DropDownList TreeView ListBox的扩展

    GridView DropDownList TreeView ListBox 的扩展 GridView DropDownList TreeView ListBox 的扩展

    Android下GridView的使用

    Android下GridView的使用,详情参见博客:http://www.cnblogs.com/plokmju/p/android_GridView.html

    Android利用GridView实现单选功能

    先看看GridView实现单选效果 如果是你需要的,你可以继续往下看了 实现起来比较简单,直接上代码 主Activity的布局,一个Button用来跳转到筛选Activity一个TextView用来显示筛选后的到的结果 &lt;?xml version=...

    projectcode网站date gridview初学范例

    projectcode网站date gridview初学范例

    Android代码-处理异步下载的库

    通过各种手段保障gridview等在有圆角和大量gif的情况下快速滑动时也能依旧极度流畅。 通过自定义的方式确保默认的加载中和加载失败的图片在任何形状的view中都能显示完整并且大小适当。 如果view使用或者继承dow

    RecyclerView GridView 矩形自适应

    博客地址:http://blog.csdn.net/dengmengxin/article/details/50238495

    CoolDragAndDrop-不规则列数的GridView上演示拖动排序效果,类似google keep.zip

    不规则列数的GridView上演示拖动排序效果,类似google keep项目地址:https://github.com/theredsunrise/AndroidCoolDragAndDropGridView效果图:如何使用:xml中创建...  android:id="@ id/coolDragAndDropGridView...

    Android下拉刷新以及GridView使用方法详解

    GridView是类似于ListView的控件,只是GridView可以使用多个列来呈现内容,而ListView是以行为单位,所以用法上是差不多的。 主布局文件,因为要做下拉刷新,所以加了一个ProgressBar,GridView的numColumns属性是指...

    GridView+BaseAdapter的使用

    &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5...

    Android实验指导.doc

    利用布局安排各种控件,设计良好用户界面 "&lt;LinearLayout " "xmlns:android="schemas.android./apk/res/android" " "android:orientation="vertical" " "android:layout_width="fill_parent" " "android:layout_...

    android GridView多选效果的实例代码

    代码如下:&lt;LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”  xmlns:tools=”http://schemas.android.com/tools”  android:background=”#000000″  android:layout_width=”fill_...

    通过开源项目来实现可以下拉刷新的GridView

    通过开源项目来实现可以下拉刷新的GridView,相关博文:http://www.cnblogs.com/tianzhijiexian/p/4023958.html

    经典cookie购物车源码[GridView实现]

    //创购物车cookie yxy .//sql8.net if (object.Equals(Request.Cookies["ztbscart"], null)) cookie = new HttpCookie("ztbscart"); else cookie = Request.Cookies["ztbscart"]; //判断是否已存在于购物车内 ...

    基于RecyclerView实现横向GridView效果

    本文实例为大家分享了RecyclerView实现横向GridView效果展示的具体代码,供大家参考,具体内容如下 要使用RecyclerView,首先要在build.gradle文件中添加依赖compile ‘com.android.support:appcompat-v7:24.1.0’ ...

    Android中实现带有头部的GridView(HeaderGridView)

    Android中实现带有头部的GridView(HeaderGridView),具体介绍,见我的博客:http://blog.csdn.net/ch1451082329/article/details/46801497

Global site tag (gtag.js) - Google Analytics