android中gallery的使用

1,创建配置文件

<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
</Gallery>

2,编写适配器,因为Gallery 需要一个适配器填充,而且填充的必须输图片,所以。。。

package com.kang.fei.gallery;

import android.content.Context;
import android.content.res.TypedArray;
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 {

	private Context context;
	int mGalleryItemBackground;
	private Integer[] mImageids ={
			R.drawable.sample_0,R.drawable.sample_1,
			R.drawable.sample_2,R.drawable.sample_3,
			R.drawable.sample_4,R.drawable.sample_5,
			R.drawable.sample_6
	};
	
	public ImageAdapter(Context context){
		this.context = context;
		//TypedArray实例是个属性的容器,context.obtainStyledAttributes()方法返回得到
		TypedArray a = context.obtainStyledAttributes(R.styleable.HelloGallery);
		mGalleryItemBackground = a.getResourceId
		(R.styleable.HelloGallery_android_galleryItemBackground, 0);
		a.recycle();
	}
	
	public int getCount() {
		return mImageids.length;
	}

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

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

	public View getView(int position, View convertView, ViewGroup parent) {
		
		ImageView i = new ImageView(context);
		i.setImageResource(mImageids[position]);
		i.setLayoutParams(new Gallery.LayoutParams(150,100));
		i.setScaleType(ImageView.ScaleType.FIT_XY);
		i.setBackgroundResource(mGalleryItemBackground);
		return i;
		
	}

}

3,编写一个attrs.xml文件,防止在values文件颊下

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

4,编写主层序类

package com.kang.fei.gallery;

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

public class GalleryActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemClickListener(new OnItemClickListener() {

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

相关推荐