Skip to content Skip to sidebar Skip to footer

Android, Add View With Height In Percentage

i wanna add a view with a 100% width and X%(e.g: lets make it 40%) to the parent view i have this: private RelativeLayout getParentView(){ return (RelativeLayout) MyActivity.t

Solution 1:

You can do this by simply getting the screen width

publicstaticintgetScreenWidth(Context context) {
    DisplayMetricsdisplayMetrics=newDisplayMetrics();
    ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.widthPixels;
}

Multiply that by the percentage and give the parameters to view like this:

//For 40% height according to the screen width.
view.getLayoutParams().height = (int) (getScreenWidth(mContext) * 0.40);

Hope this helps.

Solution 2:

privatestaticvoidupdateDimen(Activity activity){
    DisplayMetricsdisplayMetrics=newDisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    screenHeight = displayMetrics.heightPixels;
    screenWidth = displayMetrics.widthPixels;
}

Use above code to get screen height and screen width.

Then get the instance of your Layout, get its LayoutParams instance and update the dimension

params.height = screenHeight * 0.6;params.width = screenWidth * 0.6;

Post a Comment for "Android, Add View With Height In Percentage"