Ahad Porkar
Ahad Porkar

Reputation: 1698

Using setImageDrawable to draw Dynamic icon

There is a code inside Android SDK Api Demo

i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
final int w = (int) (64 * getResources().getDisplayMetrics().density + 2f);
i.setLayoutParams(new GridView.LayoutParams(w, w));

can someone explain this code ? havnt found anything on web.

There is google doc that mention "setImageDrawable" is for draw something on screen And alsoe "GetPackageManager" for Returning PackageManager instance to find global package information. now problem is i cant find the list of icon in project folder and plus that , how can i change it show my icon instead and add event for clicking them.

Upvotes: 1

Views: 6808

Answers (2)

Kenneth Murerwa
Kenneth Murerwa

Reputation: 888

As of June, 2021, the answer by Manu Zi is now deprecated. In order to achieve the same, you would have to use ContextCompat as shown below.

In a fragment, use the following:

setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.icon))

If your code is in an activity, use the code below:

setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon))

Happy coding!!!

Upvotes: 2

Manu Zi
Manu Zi

Reputation: 2370

to the code u have postet, the first line, there u load the icon and set it.

the second is for scaling the bounds of an image to the bounds of this view, the FIT_CENTER scale it center of the screen.

the third, u calculate the width and in the fourth u set it to the imageview (set the size).

the icons u can find in the sdk folder. (\path-to-your-android-sdk-folder\platforms\android-xx\data\res)

to load you'r own icon use this:

setImageDrawable(getResources().getDrawable(R.drawable.icon));

and the listener:

    imageView.setOnClickListener(clickListener);
OnClickListener clickListener = new OnClickListener() {
    public void onClick(View v) {
               if (v.equals(imageView)) {
                  // you'r code here
               }
           }
};

Upvotes: 4

Related Questions