Search code examples
androidandroid-gallery

Android Hello Gallery does not wotk


I follow hello gallery tutorial but does not work. It displays blank screen.

I've upload the sample images in drawable folder.

Here is the main.xml code

<?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" />

The attr.xml :

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

The Activity class :

public class GalleryActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Gallery gallery = (Gallery) findViewById(R.id.gallery);
    gallery.setAdapter(new ImageAdapter(this));

    gallery.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            Toast.makeText(GalleryActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }

    });
  }
}

The ImageAdapter class :

public class ImageAdapter extends BaseAdapter {

int mGalleryItemBackground;
Context mContext;

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,
        R.drawable.sample_7 };

public ImageAdapter(Context context) {

    mContext = context;

    TypedArray attr = mContext
            .obtainStyledAttributes(R.styleable.HelloGallery);
    mGalleryItemBackground = attr.getResourceId(
            R.styleable.HelloGallery_android_galleryItemBackground, 0);
    attr.recycle();

  }

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

    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(mImageIds[position]);
    imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    imageView.setBackgroundResource(mGalleryItemBackground);

    return imageView;
  }
}

When I debug the code, I noticed that the method getView never been executed. Pleas help.

Thanks


Solution

  • Where is getCount() method in Adapter class ?? in code you posted here. You didn't copied the example code properly. Please do it first.