android 最简单的九宫格实现-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

android 最简单的九宫格实现

简介: public class GridViewFunction extends Activity { private GridView _gridview; private List list; _gridview=(GridView) findViewById(R.
public class GridViewFunction extends Activity {
private GridView _gridview;
private List<Map<String ,Object>> list;
_gridview=(GridView) findViewById(R.id.gridView1); 
list=new ArrayList<Map<String,Object>>(); 
  for (int i = 0; i < 9; i++) { 
    Map<String,Object> map=new HashMap<String, Object>(); 
    map.put("img",R.drawable.icon); 
   map.put("text",i+"item"); 
        list.add(map);  
 } 
   SimpleAdapter simple=new SimpleAdapter(getApplicationContext(), list, R.layout.gridview_item,new String[] {"img","text"},new int[]{R.id.log_item_image,R.id.log_item_text}); _gridview.setAdapter(new GridViewAdapter(this));
}

 R.layout.gridview_item 文件里面放2个。一个图片和一个文字:
主文件直接放GIRDVIEW控件。   
  <GridView    android:id="@+id/gridView1"
       android:layout_width="fill_parent"
      android:numColumns="auto_fit"
       android:stretchMode="columnWidth" 
       android:columnWidth="90dp"
    android:gravity="center"
            android:layout_height="fill_parent">
         </GridView>

这样就完成了。


当然,如果简单一点的话直接适配比较好!
代码以下:

class GridViewAdapter extends BaseAdapter{
private Context ct;
public GridViewAdapter(Context ct){
this.ct=ct;
}

private int [] img={R.drawable.imagebutton1,R.drawable.imagebutton2,R.drawable.imagebutton3,
R.drawable.imagebutton4,R.drawable.imagebutton5,R.drawable.imagebutton6,R.drawable.imagebutton7,R.drawable.imagebutton8,R.drawable.imagebutton9};
private String [] text= {
"A","B","C","D"
,"E","F","G","H"
,"I"
};
@Override
public int getCount() {
// TODO Auto-generated method stub
return text.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
WrapperImgText wrapper;
if(convertView==null){
wrapper=new WrapperImgText();
LayoutInflater layout=LayoutInflater.from(ct);
convertView=layout.inflate(R.layout.gridview_item,null);
convertView.setTag(wrapper);
convertView.setPadding(15, 15, 15, 15);
}else{
wrapper=(WrapperImgText) convertView.getTag();
}
wrapper.image=(ImageView) convertView.findViewById(R.id.log_item_image);
wrapper.tv=(TextView) convertView.findViewById(R.id.log_item_text);
wrapper.image.setBackgroundResource(img[position]);
wrapper.tv.setText(text[position]);
return convertView;
}
class WrapperImgText{
ImageView image;
TextView tv;
}
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章