2012年11月30日 星期五

Android:循環Gallery

public class MainActivity extends Activity {
private ImageAdapter imageAdapter=null;
private Gallery gallery=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery=(Gallery)findViewById(R.id.gallery1);
//設定Adapter
gallery.setAdapter(new ImageAdapter(this));
gallery.setGravity(Gravity.CENTER_HORIZONTAL);//效果目前不明     
gallery.setUnselectedAlpha(0.3f);//未選到的圖片比較暗                   
                gallery.setSpacing(20);//圖片與圖片間的間隔 
        
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
gallery.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
}


}

package com.briview.mgallery;

import ...

public class ImageAdapter extends BaseAdapter {
private Context context;
int imgArr[]={R.drawable.r0,R.drawable.r100,R.drawable.r150,R.drawable.r20};

public ImageAdapter(Context context){
this.context=context;
}
@Override
public int getCount() {
//修改返回值為無限大
return Integer.MAX_VALUE;
}

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

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

@SuppressWarnings("deprecation")
@Override
public View getView(int position, View v, ViewGroup parent) {
//new a imageview to show pic
ImageView imageview=new ImageView(context);
//參數意義為讓使用者出圖片index範圍時,跳回第一張,Ex:5%4=1
imageview.setImageResource(imgArr[position%imgArr.length]);
//set the layout,determine how the pic to show
imageview.setLayoutParams(new Gallery.LayoutParams(480,800));
imageview.setScaleType(ImageView.ScaleType.CENTER);
imageview.setBackgroundColor(Color.alpha(1)); 
return imageview;
}


}



沒有留言:

張貼留言