Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 339
Nik Avatar asked Oct 25 '25 01:10

Nik


2 Answers

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;
like image 52
Chetan Joshi Avatar answered Oct 27 '25 14:10

Chetan Joshi


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;
        }
    }
}
like image 23
Md. Nowshad Hasan Avatar answered Oct 27 '25 14:10

Md. Nowshad Hasan