getActionbar().getHeight()为0,actionbar customView失效的解决方法

    最近遇到一个难题,我在activity中使用了fragmentA,fragmentB,然后在fragmentB给actionbar自定义customView.然后通过搜索框输入,跳转到另外一个activity并有fragmentB(复用之前那个fragmentB)。发现跳转过去的fragmentA始终出不来自定义的customView.


    我立刻跳出来四个想法:

1. 搜索框也是用的actionbar,难道是它挡住我了吗?
    我找了个button加了测试代码,直接跳转过去,验证不是;

2. 是因为startActivity()跳转过去,导致不显示的吗?
    于是改动一些代码,让这个acitivy默认显示。验证不是;

3. 是因为各种layout,和customView不显示吗?
    反复检查view.发现可能性不大;

4. 是因为onOptionMenu, onCreateMenu等导致吗?似乎也不是。


最后终于找到了问题点:

在fragment的onCreateView()中如下使用的:


getActivity().getActionBar().setCustomView(
mActionbarCustomLinearLayout,
new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,

getActivity().getActionBar().getHeight()));


乍看之下,没有任何错误啊?而且在之前也用的好好的。后来发现,在activity的onCreate() onResume() , getActionBar.getHeight()有可能是0,因为还没有决定高度到底是多少。

替代方案:

ActionBar.LayoutParams layoutparams = new ActionBar.LayoutParams(
Gravity.CENTER_HORIZONTAL);
TypedArray actionbarSizeTypedArray = getActivity()
.obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
float h = actionbarSizeTypedArray.getDimension(0, 0);
actionbarSizeTypedArray.recycle();
layoutparams.height = (int) h;
layoutparams.width = screenWidth;

getActivity().getActionBar().setCustomView(
mActionbarCustomLinearLayout, layoutparams);


也有其他方法,比如如果你不是在生命周期里面,就可以使用原来的。又或者你要getActionbar().getHeight()的作用不是立刻使用,可以使用在runnable()中获取。


其实发现了问题点就好解决了,但是一开始,我们从直观的,只能发现为什么有的时候,customView出来了,有的时候,customView始终出不来。只有当意识到了actionbar的生命周期内,尚未初始化好,就解决了90%了。

猜你喜欢

转载自blog.csdn.net/jzlhll123/article/details/50316589