更改AppBarLayout高度编程Android中 [英] Change AppBarLayout height programatically in Android

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

问题描述

我想实现灵活的空间使用的图像模式,使用的本教程

I'm trying to implement Flexible Space with image pattern, using this tutorial.

一切工作正常。

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

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

我想使画面的高度,而不是1/3,以符合<一个href=\"http://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0B6Okdz75tqQscXNQY3dNdVlYeTQ/patterns-scrolling-techniques_flex_space_image_xhdpi_003.webm\"相对=nofollow>谷歌这样的例子这里模式。

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

下面是在活动的onCreate的code(布局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)));

但由于某些原因,结果是不是我期待的。我看不到应用栏在所有使用code。 (不code时,高度显示了如预期,但它从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).

推荐答案

做到这一点,而不是:

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

在原来的code我认为你计算在屏幕的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.

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

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