2015-07-11 108 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

相關問題