public class HelloGallery extends Activity {
public final static int ADDED_EXTRA = 6;
public final static Integer[] mImageIds = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7
};
Gallery g;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
if (position < ADDED_EXTRA / 2)
g.setSelection(mImageIds.length + 2, false);
if (position > mImageIds.length + ADDED_EXTRA / 2) {
g.setSelection(4, false);
}
}
public void onNothingSelected(AdapterView<?> parent) {
g.setSelection(3, false);
}
});
g.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if (position < ADDED_EXTRA / 2) {
position = mImageIds.length- (ADDED_EXTRA / 2 - position);
} else if (position >= (mImageIds.length + (ADDED_EXTRA / 2))) {
position = position - (mImageIds.length + (ADDED_EXTRA / 2));
} else {
position -= (ADDED_EXTRA / 2);
}
Toast.makeText(HelloGallery.this, "position: " + position, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
// TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
// mGalleryItemBackground = a.getResourceId(
// R.styleable.Gallery1_android_galleryItemBackground, 0);
// a.recycle();
}
public int getCount() {
return mImageIds.length + ADDED_EXTRA;
}
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(mContext);
if (position < ADDED_EXTRA / 2) {
position = mImageIds.length- (ADDED_EXTRA / 2 - position);
} else if (position >= (mImageIds.length + (ADDED_EXTRA / 2))) {
position = position - (mImageIds.length + (ADDED_EXTRA / 2));
} else {
position -= (ADDED_EXTRA / 2);
}
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
댓글 없음:
댓글 쓰기