andorid 网格视图GridView

 

 

.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/gv_1"
    android:numColumns="4"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="120dp"
    android:gravity="center"
    android:stretchMode="columnWidth">

</GridView>

.java

package com.hanqi.application3;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class UIActivity6 extends AppCompatActivity {
    int[] imid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ui6);

        GridView gv_1= (GridView)findViewById(R.id.gv_1);
        imid =new int[] {R.drawable.an1,R.drawable.an2,R.drawable.an3,
                R.drawable.an1,R.drawable.an2,R.drawable.an3,
                R.drawable.an1,R.drawable.an2,R.drawable.an3};

        gv_1.setAdapter(new MyBaseAdapter());

        gv_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(UIActivity6.this, "position =" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    class MyBaseAdapter extends BaseAdapter
    {
        @Override
        public int getCount() {
            return imid.length;
        }

        @Override
        public Object getItem(int position) {
            return imid[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //获取数据
            int Imageid = imid[position];
            ImageView iv1 = null;
            //构造视图
            if (convertView == null)
            {
                iv1= new ImageView(UIActivity6.this);
                //设置属性setLayoutParams
                iv1.setLayoutParams(new GridView.LayoutParams(120,120));
                iv1.setScaleType(ImageView.ScaleType.FIT_XY);

            }
            else
            {
                iv1 = (ImageView)convertView;
            }


            iv1.setImageResource(Imageid);

            return iv1;
        }
    }
}

 

转载于:https://www.cnblogs.com/cuikang/p/5365932.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值