在Android中以编程方式更改AppBarLayout高度

11

我正在尝试使用这个教程实现带图案的可伸缩空间。

一切都运行得很好。

请注意AppBarLayout中高度定义为192dp。

我想将高度改为屏幕的1/3,以匹配此处谷歌示例的图案

这是在活动的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且无法动态设置)。

2个回答

28

改为这样做:

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

在您的原始代码中,我认为您计算屏幕三分之一的方法有误,但您仍然应该能够看到一些东西。可能是setLP()中的LayoutParams.MATCH_PARENT没有正确导入。始终首先声明视图类型,即CoordinatorLayout.LayoutParams以确保正确。否则,例如使用Framelayout.LayoutParams将非常容易出错。


难道不应该像这样吗?: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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接