代码改变世界

使用GridView和SimpleAdapter实现手机界面常见的的九宫格

2017-05-08 19:16  做作业呀  阅读(159)  评论(0编辑  收藏  举报

1.布局文件

<GridView
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="10dp"
android:layout_gravity="center"
android:numColumns="3"
android:verticalSpacing="5dp"
android:stretchMode="columnWidth">

</GridView>


2.item



<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent">


<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/image"/>

</LinearLayout>

3.适配器和监听

public View getView(int i, View view, ViewGroup viewGroup) {
    //获取view
    if(view==null){
        view = LayoutInflater.from(context).inflate(R.layout.item,null);
    }
    ImageView img =(ImageView) view.findViewById(R.id.image);  
    ClassInfo classInfo = datas.get(i);
    img.setImageResource(classInfo.getImgId());  
    return view;
}
    List<ClassInfo> datas = new ArrayList<>();
    datas.add(new ClassInfo(R.drawable.zz1)); 
    datas.add(new ClassInfo(R.drawable.zz2)); 
    datas.add(new ClassInfo(R.drawable.zz3)); 
    datas.add(new ClassInfo(R.drawable.zz4)); 
    datas.add(new ClassInfo(R.drawable.zz5)); 
    datas.add(new ClassInfo(R.drawable.zz6)); 
    datas.add(new ClassInfo(R.drawable.zz7));
    datas.add(new ClassInfo(R.drawable.zz8)); 
    datas.add(new ClassInfo(R.drawable.zz9));  
    final CustomGridViewAdapter adapter = new CustomGridViewAdapter(getActivity(),datas);

    GridView gridView = (GridView)view.findViewById(R.id.gridview);

    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        String data = (String) adapterView.getItemAtPosition(position);
    }
});