在使用GridView时我们知道,列数是可以通过设计时的属性来设置的,列的宽度则是根据列数和GridView的宽度计算出来的。但是有些时候我们想实现列数是动态改变的效果,即列的宽度保持某个值,列的数量是可变的,我们可通过获取屏幕宽度并除以项目宽度来处理。请看下面的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); GridView lvnote = (GridView)findViewById(R.id.gridView1);
// The item width is about 200,项目宽度大概200像素
colnum = (int) (((getResources().getDisplayMetrics().widthPixels )) / );
lvnote.setNumColumns(colnum); }

 但是由于不同的Android设备可能有不同的宽度,项目宽度乘以获得的列数所得到的总宽度并不能填充整个屏幕的宽度,而给用户带来不好的用户体验,甚至我们可能还需要使行高和列宽保持一定的比例,那么如何动态调整项目的宽度和高度呢?

  我们此处是通过写一个自己的Adapter类,并改写其中的getView函数来实现的,getView是用来返回某个GridView项的部局的函数,我们在此处手动生成需要的view并设置此view的宽度和高度,最后将此view返回。

  注:使用此方法时,项目中的内容可能也需要手动去填充,请再研究

  相关文件及代码如下:

  主窗体只有一个GridView,部局文件代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center_horizontal"
android:numColumns="" > </GridView> </RelativeLayout>

GridView项所使用的部局文件只有一个TextView,命名为note_item,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:id="@+id/tvNote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" /> </LinearLayout>

 Activity类的实现代码如下:

package com.example.apptest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener; public class MainActivity extends Activity {
GridView lvnote;
ArrayList<HashMap<String, String>> mynotelist = new ArrayList<HashMap<String,String>>();
int colnum = ; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); lvnote = (GridView)findViewById(R.id.gridView1);
// The item width is about 200,项目宽度大概200像素
colnum = (int) (((getResources().getDisplayMetrics().widthPixels )) / );
lvnote.setNumColumns(colnum); HashMap<String, String> mapitem1 = new HashMap<String, String>();
mapitem1.put("note", "Hello1...");
mapitem1.put("noteid", "");
mynotelist.add(mapitem1); HashMap<String, String> mapitem2 = new HashMap<String, String>();
mapitem2.put("note", "Hello2...");
mapitem2.put("noteid", "");
mynotelist.add(mapitem2); HashMap<String, String> mapitem3 = new HashMap<String, String>();
mapitem3.put("note", "Hello3...");
mapitem3.put("noteid", "");
mynotelist.add(mapitem3); HashMap<String, String> mapitem4 = new HashMap<String, String>();
mapitem4.put("note", "Hello4...");
mapitem4.put("noteid", "");
mynotelist.add(mapitem4); HashMap<String, String> mapitem5 = new HashMap<String, String>();
mapitem5.put("note", "Hello5...");
mapitem5.put("noteid", "");
mynotelist.add(mapitem5); HashMap<String, String> mapitem6 = new HashMap<String, String>();
mapitem6.put("note", "Hello6...");
mapitem6.put("noteid", "");
mynotelist.add(mapitem6); NoteAdapter adapter = new NoteAdapter(this, mynotelist, R.layout.note_item,
new String[]{"note"},
new int[]{R.id.tvNote}); lvnote.setAdapter(adapter);
} public class NoteAdapter extends SimpleAdapter{
Context context = null; @Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// Inflate the note_item layout manually, and treat it as the item view
// 重新填充note_item部局,并把它作为项的view返回
convertView = LayoutInflater.from(context).inflate(R.layout.note_item, null);
HashMap<String, String> theMap = (HashMap<String, String>)getItem(position);
TextView txtNote = (TextView)convertView.findViewById(R.id.tvNote);
txtNote.setText(theMap.get("note").toString()); // Calculate the item width by the column number to let total width fill the screen width
// 根据列数计算项目宽度,以使总宽度尽量填充屏幕
int itemWidth = (int)(getResources().getDisplayMetrics().widthPixels - colnum * ) / colnum;
// Calculate the height by your scale rate, I just use itemWidth here
// 下面根据比例计算您的item的高度,此处只是使用itemWidth
int itemHeight = itemWidth; AbsListView.LayoutParams param = new AbsListView.LayoutParams(
itemWidth,
itemHeight);
convertView.setLayoutParams(param); return convertView;
} public NoteAdapter(Context context,
List<? extends Map<String, ?>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
this.context = context;
} } }

Android中动态设置GridView的列数、列宽和行高的更多相关文章

  1. Android中动态更新ListView(转)

    在使用ListView时,会遇到当ListView列表滑动到最底端时,添加新的列表项的问题,本文通过代码演示如何动态的添加新的列表项到ListView中.实现步骤:调用ListView的setOnSc ...

  2. Android中如何设置RadioButton在文字的右边,图标在左边

    from:http://blog.csdn.net/sunnyfans/article/details/7901592?utm_source=tuicool&utm_medium=referr ...

  3. Quartz在Spring中动态设置cronExpression (spring设置动态定时任务)

    什么是动态定时任务:是由客户制定生成的,服务端只知道该去执行什么任务,但任务的定时是不确定的(是由客户制定).      这样总不能修改配置文件每定制个定时任务就增加一个trigger吧,即便允许客户 ...

  4. Android中一个类实现的接口数不能超过七个

    近期一段时间,在开发Android应用程序的过程中,发现Android中一个类实现的接口数超过七个的时候,常常会出现超过第7个之后的接口不能正常使用.

  5. Quartz在Spring中动态设置cronExpression

    什么是动态定时任务:是由客户制定生成的,服务端只知道该去执行什么任务,但任务的定时是不确定的(是由客户制定). 这样总不能修改配置文件每定制个定时任务就增加一个trigger吧,即便允许客户修改配置文 ...

  6. 微信小程序首页index.js获取不到app.js中动态设置的globalData的原因以及解决方法

    前段时间开发了一款微信小程序,运行了也几个月了,在index.js中的onLoad生命周期里获取app.js中onLaunch生命周期中在接口里动态设置的globalData一直没有问题,结果昨天就获 ...

  7. 分别在javascript和JSP中动态设置下拉列表默认值

    一.JavaScript中动态设置select标签中<option>选项的默认值: 比如,要完成下边这个下拉列表的动态显示,并且当进行前后翻页时,下拉列表中的值自动更新为当前页码: 图1 ...

  8. 使用像素单位设置 EXCEL 列宽或行高

    在导出 Excel 的时候, 经常要需要给列设置宽度或给行设置高度, 在使用 NPOI 或 EppPlus 等组件进行操作的时候, 列宽和行高的单位都不是像素, 好像是英寸,具体是啥也说不清. 平常在 ...

  9. DataGridView使用技巧五:自动设定列宽和行高

    一.设定行高和列宽自动调整 设定包括Header和所有单元格的列宽自动调整 //设置包括Header和所有单元格的列宽自动调整 this.dgv_PropDemo.AutoSizeColumnsMod ...

随机推荐

  1. mysql 批量删除数据

    批量删除2000w数据 使用delete from table太慢 //DELIMITER DROP PROCEDURE if EXISTS deleteManyTable; create PROCE ...

  2. ArcEngine标注和注记

    转自原文 ArcEngine标注和注记 标注和注记是ArcEngine中提供的两种使用文字信息标注地图要素的方式.其中标注是作为图层的属性存在的,可以动态创建,注记作为地理要素被存储.需要注意的是Sh ...

  3. meld文件的脚本

    今天模仿着别人的脚本,结合网上的资料,摸索着写了一个简单的脚本,用来打开meld 工具.这个脚本虽然简单,但这是第一次自己写脚本,记录下来,作为自己python学习的起点.代码如下 #/use/bin ...

  4. adapter-自定义adapter的典型写法

    文章参考 http://www.cnblogs.com/mengdd/p/3254323.html import android.content.Context; import android.vie ...

  5. h5背景

    1.背景属性复习: background-image background-color background-repeat background-position background-attachm ...

  6. MYSQL添加远程用户或允许远程访问三种方法

    添加远程用户admin密码为password GRANT ALL PRIVILEGES ON *.* TO admin@localhost IDENTIFIED BY \'password\' WIT ...

  7. SQLite基础学习

    SQLite是一款轻量级数据库,集成于android中,以下从分享一下自己学习的. 在查阅资料时有一些好的说明就直接用了: 主要的curd语句 以下SQL语句获取5条记录,跳过前面3条记录 selec ...

  8. [Angular] Implement a custom form component by using control value accessor

    We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...

  9. js进阶 13-6 jquery动画效果相关常用函数有哪些

    js进阶 13-6 jquery动画效果相关常用函数有哪些 一.总结 一句话总结:animate(),stop(),finish(),delat()四个. 1.stop()方法的基本用法是什么(sto ...

  10. ajax中打开新页面使用window.open方法被拦截的解决方法

    $('.testA').unbind('click').bind('click',function(){ var result=""; $.ajax({ url:'http://l ...