android代码布局 实现的Gallery

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Activity01 extends Activity
{ LinearLayout linearLayout;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

linearLayout=new LinearLayout(this);
linearLayout.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

//获得Gallery对象
Gallery g = new Gallery(this);
g.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

//添加ImageAdapter给Gallery对象
g.setAdapter(new ImageAdapter(this));

//设置Gallery的背景
g.setBackgroundResource(R.drawable.bg0);

//设置Gallery的事件监听
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(Activity01.this,"你选择了"+(position+1)+" 号图片",
Toast.LENGTH_SHORT).show();
}
});
linearLayout.addView(g);
setContentView(linearLayout);
}

}


、、、、、、、、、、、、、、、、、、

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter
{
// 定义Context
private Context mContext;
// 定义整型数组 即图片源
private Integer[] mImageIds =
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7,
R.drawable.img8,
};

// 声明 ImageAdapter
public ImageAdapter(Context c)
{
mContext = c;
}

// 获取图片的个数
public int getCount()
{
return mImageIds.length;
}

// 获取图片在库中的位置
public Object getItem(int position)
{
return position;
}

// 获取图片ID
public long getItemId(int position)
{
return position;
}

public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageview = new ImageView(mContext);

// 给ImageView设置资源
imageview.setImageResource(mImageIds[position]);
// 设置布局 图片120×120显示
imageview.setLayoutParams(new Gallery.LayoutParams(120, 120));
// 设置显示比例类型
imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageview;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值