-1

Right now I'm working on a launcher app, in which I've made a GridView which fetches all installed apps from the device. But there are only app icons and no app names. And I wanted to put app name below it so I tried to put TextView below my app icon ImageView, but my app crashes. Any ideas how should I fix it? Here's my code: Thank you very much!

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

            if (convertView == null) {
                i = new ImageView(Apps.this);
                i.setScaleType(ImageView.ScaleType.FIT_CENTER);
                i.setLayoutParams(new GridView.LayoutParams(93, 93));
                i.setPadding(15, 15, 15, 15);


            } else {
                i = (ImageView) convertView;
            }

            ResolveInfo info = mApps.get(position);
            i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));

            return i;
        }
Ajinkya More
  • 425
  • 1
  • 3
  • 15

2 Answers2

1

Instead of building a view that contain TextView and ImageView, use CompoundDrawable. You only have to implement one TextView and set it's DrawableTop with the required icon. This will do the job.

From the XML file

<TextView
    android:id="@+id/my_textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableTop="@drawable/my_icon"
    android:gravity="center"
    />

Or you can do it programmatically using the following:

myTextView.setCompoundDrawablesWithIntrinsicBounds(null, topDrawable, null, null);
Sami Eltamawy
  • 9,874
  • 8
  • 48
  • 66
1

Simply use a TextView as the image container, by using a compound drawable: http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds(int,%20int,%20int,%20int)

So, you'll set 1 View to replace 2 ones, with UI simplification and performance improvements, as side-effects.

A little example:

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

        if (convertView == null) {
            t = new TextView(Apps.this);
            t.setLayoutParams(new GridView.LayoutParams(93, 93));
            t.setPadding(15, 15, 15, 15);

            ResolveInfo info = mApps.get(position);
            Drawable drw = info.activityInfo.loadIcon(getPackageManager());

            t.setCompoundDrawablesWithIntrinsicBounds(null, drw, null, null);
            //t.setText("Some Text");
            t.setText(info.activityInfo.loadLabel(getPackageManager()).toString());

        } else {
            t = (TextView) convertView;
        }

        return t;
    }

[EDIT]

Once you return the View (t, the TextView), you can get the drawable by using getCompoundDrawables(): http://developer.android.com/reference/android/widget/TextView.html#getCompoundDrawables()

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115