• 8
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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;
  • 1
Reply Report

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);
}
  • 0
Reply Report

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;
        }
    }
}
  • 0
Reply Report