Search code examples
androidandroid-gallery

Adding text to each image item of a Gallery in Android


I have a image Gallery, and i want to show the last modified data below each image, but nothing is shown in the TextView (but yes in the ImageView). This is my adapter.

public class ImageAdapter extends BaseAdapter implements SpinnerAdapter {

    private Context context;
    private Drawable[] pics;
    private String[] filePaths;

    public ImageAdapter(Context context, Drawable[] pics, String[] filePaths) {
        this.context=context;
        this.pics =pics;
        this.filePaths=filePaths;
    }

    @Override
    public int getCount() {
        return pics.length;
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v=view;
        ImageView imageView;
        TextView textView;


        if(v==null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.gallery_item, null);
        }

        imageView=(ImageView)v.findViewById(R.id.galleryImageView);
        textView=(TextView)v.findViewById(R.id.galleryTextView);

        imageView.setLayoutParams(new Gallery.LayoutParams(115, 100));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8,8,8,8);

        File f=new File(filePaths[i]);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy");
        Date lastModified=new Date(f.lastModified());

        imageView.setImageDrawable(pics[i]);
        textView.setText(simpleDateFormat.format(lastModified));

        return imageView;
    }

}

And this is my xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/galleryImageView" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/galleryTextView"
        android:textColor="#000"/>
</LinearLayout>

As I said, the image is shown, but there is no text below it.


Solution

  • You are returning ImageView instead of View(Layout).

    Use this code

    return v;