Android Gallery

首先展示一下效果图


操作步骤如下:

1)用eclipse创建Android Application"GalleryApp"。


2)修改activity_main.xml代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3)将需要的图片复制到drawable-hdpi


4)在values下面建一个叫attrs 的XML文件。
里面内容写如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>
</resources>

5)修改MainActivity.java代码如下

package com.example.galleryapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.*;
import android.widget.*;


public class MainActivity extends Activity {

private Gallery gallery1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery1 = (Gallery) findViewById(R.id.gallery1);
gallery1.setAdapter(new ImageAdapter(this));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;

//显示的图片集合
private Integer[] mImageIds = { 
R.drawable.image1, 
R.drawable.image2,
R.drawable.image3, 
R.drawable.image4, 
R.drawable.image5
};

public ImageAdapter(Context context) {
mContext = context;

TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
a.recycle();
}

@Override
public int getCount() {
return mImageIds.length;
}

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

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


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


i.setImageResource(mImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
//设置图片的大小
i.setLayoutParams(new Gallery.LayoutParams(400, 600));

// The preferred Gallery item background
i.setBackgroundResource(mGalleryItemBackground);

return i;
}
}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值