GridView用于在界面上按行、列分布的方式来显示多个组件。
< LinearLayout 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 = "com.example.gridview.MainActivity" >
< GridView
android:id = "@+id/gridview"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:numColumns = "auto_fit" //每行显示多少列 auto_fit 自动适应
android:horizontalSpacing = "10dp" //两列之间的间距
android:verticalSpacing = "10dp" //两行之间的间距
></ GridView >
</ LinearLayout >
<? 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" >
< ImageView
android:id = "@+id/image"
android:layout_height = "wrap_content"
android:layout_width = "wrap_content"
android:background = "@drawable/ic_launcher"
/>
< TextView
android:id = "@+id/text"
android:layout_height = "wrap_content"
android:layout_width = "wrap_content"
android:hint = "@string/hello_world"
/>
</ LinearLayout >
public class MainActivity extends Activity implements OnItemClickListener {
private GridView gridView ;
private List<Map<String, Object>> data ;
private int [] icon ={};
private String[] iconname ={};
private SimpleAdapter simpleAdapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
gridView =(GridView) findViewById(R.id. gridview );
//准备数据源
//新建适配器(simpleAdapter)
//gridview 加载适合配器
//gridview 配置事件监听器(Onitemclicklistener )
data = new ArrayList<Map<String, Object>>();
getdata();
simpleAdapter = new SimpleAdapter( this , getdata(), R.layout. item , new String[]{ "image" , "text" }, new int []{R.id. image ,R.id. text });
gridView .setAdapter( simpleAdapter );
//监听器每一列图标的点击事件。
gridView .setOnItemClickListener( this );
}
private List<Map<String, Object>> getdata() {
Map<String, Object> map= new HashMap<String,Object>();
for ( int i = 0; i < icon . length ; i++) {
map.put( "image" , icon [i]);
map.put( "text" , iconname [i]);
}
data .add(map);
return data ;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast. makeText( this , position, Toast. LENGTH_LONG ).show();
}
}