当前位置: 首页 > 工具软件 > Gallery > 使用案例 >

android 画廊 gallery

寿伟
2023-12-01

mainActiviy

package com.example.mygallary;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class MainActivity extends Activity {
	Gallery gal;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageAdapter adapter=new ImageAdapter(this);
        gal=(Gallery)findViewById(R.id.gal);
        gal.setAdapter(adapter);
        gal.setSelection(Integer.MAX_VALUE/2);
        
        
        
        
    }
    
    public  class  ImageAdapter  extends BaseAdapter{
    	Context context=null;
    	int mGalleryItemBackground;
    	public ImageAdapter(Context context){
    		this.context=context;
  	TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);//加载资源文件
    		 mGalleryItemBackground = a.getResourceId(
    		 R.styleable.HelloGallery_android_galleryItemBackground, 0);//设置Gallery的背景布局
    		                 a.recycle();
    	}
    	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return Integer.MAX_VALUE;
		}
		int ids[]={R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s4,R.drawable.s5,R.drawable.s6};

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView imageView=null;
			if(convertView==null){
				imageView=new ImageView(context);
				convertView=imageView;
			}
			imageView.setImageResource(ids[position%6]);
			imageView.setBackgroundResource(mGalleryItemBackground);
			imageView.setLayoutParams(new Gallery.LayoutParams(260,220));
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			return imageView;
		}
    	
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
 values 包下attr.xml

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

drawable包下6张图片S1 S2...



 类似资料: