0

XML code

<ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:id="@+id/imageView"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:background="@drawable/pz"
            android:layout_marginTop="5dp" />

I wrote it like this in java

    ImageView imageView = new ImageView(MainActivity.this);
    imageView.setImageResource(R.drawable.pz);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    MainActivity.this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = displaymetrics.widthPixels;
    int height = 300;
    imageView.setLayoutParams(new ViewGroup.LayoutParams(width, height));

    imageView.setId(i + 1);
    li.addView(imageView);

But it looks strange , i want to change height to eg. 200 , instead of changing height it change width.Is there any better way to make it i just want width to MATCH_PARENT and height to be 200dp?

Praziluk
  • 21
  • 8
  • Possible duplicate of [Programatically set height on LayoutParams as density-independent pixels](http://stackoverflow.com/questions/5959870/programatically-set-height-on-layoutparams-as-density-independent-pixels) – dthulke Nov 13 '16 at 14:28

1 Answers1

0

if you want to set any layout parameter to wrap_content or match_parent you should set ViewGroup.LayoutParams.MATCH_PARENT orViewGroup.LayoutParams.MATCH_PARENT constants for constructor parameters

and the constructor gets parameters in px so you have to change it to dp you can use this link

Community
  • 1
  • 1
Farid
  • 1,024
  • 9
  • 16