简体   繁体   中英

How to write XML code for width and heigh in Java

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?

if you want to set any layout parameter to wrap_content or match_parent you should set ViewGroup.LayoutParams.MATCH_PARENT or ViewGroup.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM