简体   繁体   中英

Set height of the view programmatically on Android

How to set height of the view based on screen height?

<View
    android:id="@+id/myRectangleView"
    android:layout_width="200dp"
    android:layout_height="50dp" //view height
    android:background="@drawable/rectangle"/>

Currently the height is set to 50dp. I need to set height of the view as follows:

View Height     Screen Size 
32 dp           ≤ 400 dp
50 dp           > 400 dp and ≤ 720 dp
90 dp           > 720 dp

You can get LayoutParams Object of View and then set Height and Width to view Dynamically like below code:

View view = (View)findViewById(R.id. myRectangleView);
LayoutParms layoutParams = view.getLayoutParms();
layoutParms.height = 200;
layoutParms.width  = 300;

You can use this :

public static int getScreenHeightInDP(Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

    float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;

    return Math.round(screenHeightInDP);
}

I have tried this solution in mine. Hope its OK for you.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View view = (View) findViewById(R.id.myRectangleView);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height = 500;

        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float density = getResources().getDisplayMetrics().density;
        float dpHeight = outMetrics.heightPixels / density;

        if ((int) dpHeight <= 400) {
            layoutParams.height = 32;
        } else if ((int) dpHeight > 400 && dpHeight <= 720) {
            layoutParams.height = 50;
        } else if ((int) dpHeight > 720) {
            layoutParams.height = 90;
        }
    }
}

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