使用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"
android:orientation="vertical"
tools:context="com.example.gridviewdemo.MainActivity" >
<!-- android:numColumns="" 每一行显示多少列
android:horizontalSpacing=""
android:verticalSpacing="" -->
<GridView
android:id="@+id/my_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
</LinearLayout>
GridView的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"
android:gravity="center"
android:background="#000000">
<ImageView
android:id="@+id/image"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_launcher"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="文字"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnItemClickListener{
private GridView gridView ;
private List<Map<String, Object>> dataList;
private int[] icon = {R.drawable.address_book,R.drawable.calendar,
R.drawable.camera,R.drawable.clock,R.drawable.games_control,
R.drawable.messenger,R.drawable.ringtone,R.drawable.settings,
R.drawable.speech_balloon,R.drawable.weather,R.drawable.world,
R.drawable.youtube};
private String[] iconName = {"通讯录","日历","相机","时钟","游戏","短信","铃声",
"设置","语音","天气","浏览器","视频"};
private SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.my_grid);
//1.准备数据源
//2.新建适配器(SimpleAdapter)
//3.GridView加载适配器
//4.GridView配置事件监听器(OnItemClickListener)
dataList = new ArrayList<Map<String,Object>>();
// getData();
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<String, Object>();
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, "position ="+position, Toast.LENGTH_SHORT).show();
}
}
实现效果: