Forget on my previously answer not working on all versions. The right approach is to find out navigation bar height and add bottom margin -navigationBarHeight. This is full working example work on all 4.1+ versions:
public static int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
return 0;
}
@SuppressLint("NewApi")
private int getRealScreenSize(boolean returnWidth) {
final DisplayMetrics metrics = new DisplayMetrics();
Display display = getActivity().getWindowManager().getDefaultDisplay();
Method mGetRawH = null, mGetRawW = null;
//Not real dimensions
display.getMetrics(metrics);
int width = metrics.heightPixels;
int height = metrics.widthPixels;
try {
// For JellyBeans and onward
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
display.getRealMetrics(metrics);
//Real dimensions
width = metrics.heightPixels;
height = metrics.widthPixels;
} else {
mGetRawH = Display.class.getMethod("getRawHeight");
mGetRawW = Display.class.getMethod("getRawWidth");
try {
width = (Integer) mGetRawW.invoke(display);
height = (Integer) mGetRawH.invoke(display);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (NoSuchMethodException e3) {
e3.printStackTrace();
}
if (returnWidth) {
return width;
} else {
return height;
}
}
Following example code need to put somewhere after surface was created:
RelativeLayout.LayoutParams lp = (LayoutParams) surfaceView.getLayoutParams();
int screenHeight = getRealScreenSize(false);
int screenWidth = getRealScreenSize(true);
int navigationBarHeight = getNavigationBarHeight(getActivity());
lp.height = (int) (screenWidth / (16d / 9d));
lp.width = screenWidth;
int k = (lp.height - screenHeight) / 2;
lp.setMargins(0, -k, 0, (-k) - navigationBarHeight);
surfaceView.setLayoutParams(lp);
Note that surface view must have parent RelativeLayout.