Android中实现手机相册最简单的方法就是使用GridView,GridView是一个简单容易使用的控件,不管你有没有使用都不会觉得复杂,废话不多说先看效果图。
效果图
图片.png
怎么样实现当前的效果呢?跟着老司机的节奏 一起来探讨吧。
1.新建一个工程MainActivity的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:horizontalSpacing="1dp"
android:numColumns="5"
android:verticalSpacing="1dp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="240dp"
android:layout_height="240dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
/>
</LinearLayout>
2.cell布局 (我们的cell布局局相当于listview中的 item_layout,这个布局文件是要在适配器里面使用)代码如下:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cellImage"
android:layout_width="80dp"
android:layout_height="80dp" />
3.Activity的代码:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private GridView gridView;
private List<Map<String, Object>> listItems;
private ImageView imageView;
private int[] imageIds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageIds = new int[]{
R.mipmap.abc_btn_check_to_on_mtrl_000, R.mipmap.abc_btn_check_to_on_mtrl_015, R.mipmap.abc_btn_radio_to_on_mtrl_000, R.mipmap.abc_btn_radio_to_on_mtrl_015,
R.mipmap.abc_ic_star_black_16dp, R.mipmap.abc_ic_star_black_36dp, R.mipmap.abc_ic_star_black_48dp
};
listItems = new ArrayList<>();
for (int i = 0; i < imageIds.length; ++i) {
Map<String, Object> listItem = new HashMap<>();
listItem.put("image", imageIds[i]);
listItems.add(listItem);
}
initView();
}
private void initView() {
gridView = (GridView) findViewById(R.id.gridView);
imageView = (ImageView) findViewById(R.id.imageView);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.cell,
new String[]{"image"}, new int[]{R.id.cellImage});
gridView.setAdapter(simpleAdapter);
gridView.setOnItemSelectedListener(this);
gridView.setOnItemClickListener(this);
imageView.setImageResource(imageIds[0]);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
imageView.setImageResource(imageIds[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
imageView.setImageResource(imageIds[position]);
}
}
其它技术文章:http://www.jianshu.com/u/a5ad093cffe8
demo 关注我的公众号:回复(相册gridview) 得到下载链接