I'm trying to implement Flexible Space with image pattern, using this tutorial.
Everything works fine.
Notice the height definition of the AppBarLayout which is 192dp.
I'd like to make the height 1/3 of the screen instead, to match this google example for the pattern here.
Here's the code in the activity's onCreate (the layout xml is exactly the same as in the tutorial):
AppBarLayout appbar = (AppBarLayout)findViewById(R.id.appbar);
float density = getResources().getDisplayMetrics().density;
float heightDp = getResources().getDisplayMetrics().heightPixels / density;
appbar.setLayoutParams(new CoordinatorLayout.LayoutParams(LayoutParams.MATCH_PARENT, Math.round(heightDp / 3)));
But for some reason, the result is not what I'm expecting. I can't see the app bar at all with this code. (without the code, the height shows as expected but it's from XML and can't be set dynamically).
Do this instead:
AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
float heightDp = getResources().getDisplayMetrics().heightPixels / 3;
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = (int)heightDp;
In your original code I think that you calculation for 1/3 of the screen was wrong, but you still should have seen something. It could be that the LayoutParams.MATCH_PARENT in the setLP() wasn't imported correctly. Always declare the view type first, i.e. CoordinatorLayout.LayoutParams just to make sure. Otherwise it can be easy to use a Framelayout.LayoutParams, for instance.