<GridView
android:layout_marginTop="10dp"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:layout_width="wrap_content"
android:id="@+id/gv_view"
android:layout_height="wrap_content" />
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:gravity="center"
android:background="@android:color/black"
android:orientation="vertical">
<ImageView
android:src="@mipmap/ic_launcher"
android:id="@+id/iv_icon"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:layout_marginTop="5dp"
android:text="默认文字"
android:textColor="@android:color/white"
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
主要逻辑
package com.example.gridview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
@Bind(R.id.gv_view)
GridView gvView;
@Bind(R.id.activity_main)
RelativeLayout activityMain;
private List<Map<String,Object>> dataList;
private int[]icon={R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};
private String[]iconName={"1","2","3","4","5","6","7","8","9","10","11","12"};
private SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//准备数据源
// 新建适配器
// GridView加载适配器
//GridView配置监听器(OnItemClickLisener)
dataList=new ArrayList<>();
// getData();
simpleAdapter = new SimpleAdapter(this,getData(),R.layout.item,new String[]{"image","text"},new int[]{R.id.iv_icon,R.id.tv_name});
gvView.setAdapter(simpleAdapter);
gvView.setOnItemClickListener(this);
}
private List<Map<String,Object>> getData() {
for (int i = 0; i < icon.length; i++) {
HashMap<String, Object> hm = new HashMap<>();
hm.put("image",icon[i]);
hm.put("text",iconName[i]);
dataList.add(hm);
}
return dataList;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "我是"+iconName[position], Toast.LENGTH_SHORT).show();
}
}