2015-07-11 112 views
7

我试图使用this tutorial以图像模式实现灵活空间。在Android中以编程方式更改AppBarLayout高度

一切工作正常。

请注意AppBarLayout的高度定义是192dp。

我想使屏幕的高度为1/3,以匹配this google example for the pattern here

下面是活动的onCreate代码(布局XML是完全一样的教程):

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))); 

但由于某些原因,结果是不是我期待的。这段代码根本看不到应用栏。 (没有代码,高度如预期显示,但它来自XML并且不能动态设置)。

回答

23

而是执行此操作:

AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar); 
    float heightDp = getResources().getDisplayMetrics().heightPixels/3; 
    CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams(); 
    lp.height = (int)heightDp; 

在你原来的代码,我认为你计算在屏幕的1/3是错误的,但你还是应该看到的东西。可能是setLP()中的LayoutParams.MATCH_PARENT未正确导入。总是首先声明视图类型,即CoordinatorLayout.LayoutParams来确保。否则,例如,可以很容易地使用Framelayout.LayoutParams。

+0

是不是应该这样?:float density = mParentActivity.getResources()。getDisplayMetrics()。density; float heightDp = mParentActivity.getResources()。getDisplayMetrics()。heightPixels/density; – David

3

若干方法划分,百分比或重量的屏幕高度的编程改变AppBarLayout高度:

private AppBarLayout appbar; 

/** 
* @return AppBarLayout 
*/ 
@Nullable 
protected AppBarLayout getAppBar() { 
    if (appbar == null) appbar = (AppBarLayout) findViewById(R.id.appbar); 
    return appbar; 
} 

/** 
* @param divide Set AppBar height to screen height divided by 2->5 
*/ 
protected void setAppBarLayoutHeightOfScreenDivide(@IntRange(from = 2, to = 5) int divide) { 
    setAppBarLayoutHeightOfScreenPercent(100/divide); 
} 

/** 
* @param percent Set AppBar height to 20->50% of screen height 
*/ 
protected void setAppBarLayoutHeightOfScreenPercent(@IntRange(from = 20, to = 50) int percent) { 
    setAppBarLayoutHeightOfScreenWeight(percent/100F); 
} 

/** 
* @param weight Set AppBar height to 0.2->0.5 weight of screen height 
*/ 
protected void setAppBarLayoutHeightOfScreenWeight(@FloatRange(from = 0.2F, to = 0.5F) float weight) { 
    if (getAppBar() != null) { 
     ViewGroup.LayoutParams params = getAppBar().getLayoutParams(); 
     params.height = Math.round(getResources().getDisplayMetrics().heightPixels * weight); 
     getAppBar().setLayoutParams(params); 
    } 
} 

如果你想跟着材料设计准则的高度应等于默认高度加内容增量 https://www.google.com/design/spec/layout/structure.html#structure-app-bar

相关问题