任务要求:
使用GridView和SimpleAdapter实现手机界面常见的的九宫格,图片可以任意选择,注意图片的大小要一致
思路:
布局就不说了,代码实现部分先准备数据源 声明一个List集合,集合中的对象是map对象,map对象调用方法传入数据完成数据源准备 然后创建simpleaapter绑定,最后为图片添加了一个监听器,点击图片后会在九宫格图片下方显示这张图片。
布局:
main_activity
TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/hello" />
fragment_grid
grid_item
java代码:
GridFragment:
public class GridFragment extends Fragment {
private GridView grid_photo;
private SimpleAdapter simpleAdapter;
private ArrayList< HashMap> photo;
private ImageView img1;
//将图片资源打包到集合中
private int []icon = {
R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,
R.drawable.a6,R.drawable.a7,R.drawable.a8,R.drawable.a9};
public GridFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_grid, container, false);
//加载相关控件
grid_photo = (GridView)view.findViewById(R.id.grid_photo);
img1 = (ImageView)view.findViewById(R.id.img1);
//创建适配器并绑定
simpleAdapter = new SimpleAdapter(getActivity(),getData(),
R.layout.grid_item,new String[]{"cat"},new int[]{R.id.img});
grid_photo.setAdapter(simpleAdapter);
//为九宫格图片添加监听器
grid_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
img1.setImageResource(icon[position]);
}
});
return view;
}
//相关数据源的获取
public ArrayList> getData() {
photo = new ArrayList>();
for (int i=0;i map = new HashMap();
map.put("cat", icon[i]);
photo.add(map);
}
return (ArrayList>) photo;
}
}
在相关数据源的获取这里原本的添加数据的方法是一个个put,后面找到个是代码简洁的方法是利用一个for循环这样只用写一个put方法就可以获取9个数据源