I have this problem when coding a gallery view in Android. The images appear (as expected) in the top screen of the screen and when they are clicked they say what image is selected (again as expected). However, the image that is selected is not displayed in the imageView. My code is below:
public class MainActivity extends Activity {
Integer[] imageIDs = {
R.drawable.fourfromunimon,
R.drawable.fourfromunisat,
R.drawable.fourfromunisun,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
@SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v,
int position, long id)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
// Display the image
ImageView imageView =
(ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
Context context;
int itemBackground;
public ImageAdapter(Context c)
{
context = c;
TypedArray a = obtainStyledAttributes(
R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground,
0);
a.recycle();
}
public int getCount(){
return imageIDs.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 imageView;
if (convertView == null){
imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(
ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(
new Gallery.LayoutParams(450, 200));
}else{
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
Any help would be greatly appreciated as I do not have the foggiest idea where I could be going wrong.