GridView视图

本文实现如下效果

 

Test_Grid.java

public class Test_Grid extends Activity {
    private GridView gridview;
    private int[] ids={R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s4,R.drawable.s5};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid);
        gridview =(GridView)findViewById(R.id.girdview);
        //设置一行显示几个
        gridview.setNumColumns(3);
        gridview.setAdapter(new MyGirdAdapter());
        gridview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(Test_Grid.this, ""+position, 1).show();
                
            }
        });
    }

    private class MyGirdAdapter extends BaseAdapter
    {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return ids.length;
        }

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView image;
            if(convertView==null)
            {
                image=new ImageView(Test_Grid.this);
                image.setLayoutParams(new GridView.LayoutParams(180,180));
                image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                image.setPadding(6, 6, 6, 6);
            }
            else
                image=(ImageView)convertView;
            
            image.setImageResource(ids[position]);
            return image;
        }
        
    }

}


grid.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6     
 7     <GridView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:id="@+id/girdview" />
11     
12 
13 </LinearLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值