实现效果图:原图效果,以及点击后打印信息效果
activity_main.xml文件:
<!--
numColumns:每一行显示多少列
horizontalSpacing:两列之间的间距
verticalspacing:两行之间的间距
-->
<GridView
android:layout_marginTop="10dp"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:id="@+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</GridView>
新添的item.xml文件:
<!--建立两个空的控件以用来后面的载入-->
<ImageView
android:id="@+id/image"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:layout_marginTop="5dp"
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
mainactivity.java文件:
public class MainActivity extends Activity implements AdapterView.OnItemClickListener{
//定义以及初始化数据
private GridView gridView;
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={"通讯录","日历","照相机","时钟","游戏"
,"短信","铃声","设置","语音","天气","浏览器","视频"};
private SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化gridView
gridView=(GridView)findViewById(R.id.gridView);
/*
1.准备数据源; 2.新建适配器; 3.GridView加载适配器;4.GridView配置事件监听器
*/
dataList=new ArrayList<>();
adapter=new SimpleAdapter(this,getData(),R.layout.item,new String[]{"image","text"},
new int[]{R.id.image,R.id.text});
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
private List<Map<String,Object>> getData(){
for(int i=0;i<icon.length;i++){
Map<String,Object>map=new HashMap<>();
map.put("image",icon[i]);
map.put("text",iconName[i]);
dataList.add(map);
}
return dataList;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this,"我是"+iconName[position],Toast.LENGTH_SHORT).show();
Log.i("tag","我是"+iconName[position]);
}
}
要注意,因为这里设置了不显示标题栏,所以要在androidmainfest.xml中去定义主题样式:
android:theme="@android:style/Theme.Black.NoTitleBar"
定义完后,要在mainactivity.java文件中修改它的继承对象为activity.否则会报错