在Android中以编程方式更改AppBarLayout的高度 [英] Change AppBarLayout height programmatically in Android

查看:461
本文介绍了在Android中以编程方式更改AppBarLayout的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一切正常.

请注意AppBarLayout的高度定义为192dp.

Notice the height definition of the AppBarLayout which is 192dp.

我想改为屏幕的高度1/3,以匹配

I'd like to make the height 1/3 of the screen instead, to match this google example for the pattern here.

以下是活动的onCreate中的代码(布局xml与教程中的完全相同):

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

但是由于某种原因,结果不是我所期望的.使用此代码,我根本看不到应用程序栏. (没有代码,高度会按预期显示,但来自XML,因此无法动态设置).

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;

在您的原始代码中,我认为您为屏幕的1/3计算是错误的,但是您仍然应该看到一些内容. setLP()中的LayoutParams.MATCH_PARENT可能未正确导入.请务必先声明视图类型,即CoordinatorLayout.LayoutParams以确保.否则,例如,可以很容易地使用Framelayout.LayoutParams.

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.

这篇关于在Android中以编程方式更改AppBarLayout的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆