0

I am trying adding imageView programmatically, but don't make same size in different screens. I tried many scale codes, but don't have any good result.

screens: screens' image

here is my code:

public class Explore extends Fragment {

  public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                           Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.tab, container, false);

    LinearLayout linearLayout= new LinearLayout(getActivity());
    linearLayout.setOrientation(LinearLayout.VERTICAL);

    linearLayout.setLayoutParams(new LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));

    final float scale = view.getContext().getResources().getDisplayMetrics().density;

    int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, getResources().getDisplayMetrics());
    int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 82, getResources().getDisplayMetrics());

    int lastWidth = (int) (width * scale + 0.5f);
    int lastHeight = (int) (height * scale + 0.5f);

    ImageView imageView = new ImageView(getActivity());
    UrlImageViewHelper.setUrlDrawable(imageView, "https://example.com/example.jpg");

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(lastWidth, lastHeight);
    imageView.setLayoutParams(lp);


    linearLayout.addView(imageView);

    return linearLayout;
  }

}
mess34
  • 1
  • 1
  • 1

1 Answers1

0

Looks like the issue is not the ImageView but the size of the image that you are adding. You are correct in observing that the same image will display differently depending on the attributes of the screen on which it is displayed. The goal, however, is to properly display or scale the image bitmap itself, independent from the size of the ImageView.

For example, if you were to add this ImageView using XML there is an attribute known as android:scaleType which controls how the image is displayed within the ImageView. Depending on how this attribute is set, the ImageView will retain the desired size but scale the contents to fit within its bounds.

This attribute can also be set programatically:

imageView.setScaleType(ImageView.SCALE_TYPE);

You should consider looking into the different scale types to see if one fits your needs. If it does not, there are other ways to create thumbnail or alternate sized images before setting your ImageView

Community
  • 1
  • 1
Rarw
  • 7,645
  • 3
  • 28
  • 46
  • Thanks for your reply. I can't fix still. i tried all setScaleType Types but dont have any result. How I fix my code? – mess34 Jul 07 '14 at 20:44
  • I would get rid of the manual scaling you're doing on the image view first. What is UrlImageViewHelper? Can you show me the code for that method. – Rarw Jul 07 '14 at 21:03