一、简单写法
activity_example.xml
<?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">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
></GridView>
</LinearLayout>
ExampleActivity.java
package com.administrator.gridviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.List;
/**
* GridView展示文字
*/
public class ExampleActivity extends Activity {
private GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
gridView= (GridView) findViewById(R.id.gridview);
List<String> strList=new ArrayList<String>();
for(int i=0;i<9;i++)
{
strList.add("haha"+i);
}
//最简单的适配器,数组适配器
ArrayAdapter<String>arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,strList);
gridView.setAdapter(arrayAdapter);
}
}
二、用GridView展示已安装的应用
(一)、首先需要GridView展示的单条条目布局:
item_grid_view.xml
<?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">
<ImageView
android:id="@+id/img_appIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/tv_appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="测试"
android:layout_marginTop="5dp"/>
</LinearLayout>
(二)、然后需要把在主要引用的页面中,创建GridView用于加载条目的布局位置
activity_example2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMo