main xml
<GridView
android:numColumns="3"
android:stretchMode="columnWidth"
android:gravity="center"
android:verticalSpacing="5dp"
android:horizontalSpacing="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/grid_view">
</GridView>
gridview—item xml
<ImageView
android:id="@+id/image_view"
android:layout_width="100dp"
android:layout_height="100dp" />
main java
public class MainActivity extends AppCompatActivity {
private GridView grid_view;
private SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid_view=(GridView)findViewById(R.id.grid_view);
adapter = new SimpleAdapter(this,getData(),
R.layout.gridview_item,
new String[]{"image_view"},
new int[]{R.id.image_view});
grid_view = (GridView) findViewById(R.id.grid_view);
grid_view.setAdapter(adapter);
grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = (String) grid_view.getItemAtPosition(position);
}
});
}
private List<HashMap<String, Object>> getData() {
List<HashMap<String, Object>> datas = new ArrayList<>();
// 给list增加一条数据
HashMap<String, Object> data = new HashMap<>();
// Map映射添加数据
data.put("image_view", R.mipmap.h);
// 将这个map放到list中
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhhhhhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhhhhhhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhhhh);
datas.add(data);
data = new HashMap<>();
data.put("image_view", R.mipmap.hhhhhhh);
datas.add(data);
return datas;
}
}
![]()