Reputation: 51
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
Upvotes: 4
Views: 3014
Reputation: 626
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;
}
}
}
Upvotes: 1
Reputation: 5721
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;
Upvotes: 3
Reputation: 1660
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);
}
Upvotes: 0