【问题标题】:ButterKnife inside fragment and toolbar heightButterKnife 内部片段和工具栏高度
【发布时间】:2015-02-15 13:43:54
【问题描述】:

我开始使用 ButterKnife,我发现它在片段内部工作,视图膨胀。

但我有一个问题,是否有可能获得不膨胀的视图?

例如,我的 MainActivity 中有一个工具栏,但片段中没有。我可以使用 ButterKnife 访问此工具栏吗?

还有其他问题。我尝试使用以下方法获取工具栏高度:

Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
int toolbarHeight = toolbar.getHeight();

但是这个返回总是 0。如何直接从视图中获取工具栏的大小? 现在我正在使用:

 getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValueToolbarHeight, true);

但我真的想从视图中获取工具栏。

【问题讨论】:

  • 如果您在 oncreate 内部调用以获取高度,它将返回零。加载布局后调用它
  • 如果您想管理活动的视图,应该由活动管理它并将结果传递给感兴趣的片段。我已经回答了一个关于这个话题的问题:stackoverflow.com/questions/17436298/…。所以通过接口你告诉你的活动做某事,活动做它(活动的唯一条件是实现接口),然后活动将结果发送到你想要的片段(或者回到同一个或另一个活动)。

标签: android height fragment toolbar butterknife


【解决方案1】:

初始化视图并在创建方法中调用该方法

 view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @SuppressLint("NewApi")
     @SuppressWarnings("deprecation") 
    @Override 
    public void onGlobalLayout() {
     //now we can retrieve the width and height 
    int width = view.getWidth(); 
    int height = view.getHeight(); 
    //... //do whatever you want with them //... //this is an important step not to keep receiving callbacks: //we should remove this listener //I use the function to remove it based on the api level!
     if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
     view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
     else
     view.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
    } });

【讨论】:

  • 好的,谢谢您提供此信息 :)。关于 ButterKnife 你能给我一个答案来关闭这个吗?
  • 我没有用过黄油刀,但如果你的初始化代码在 main 活动中,那么你可以
  • 我也注入了 MainActivity,但在片段中注入不适用于所有未膨胀的视图
猜你喜欢
  • 2016-12-20
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 2015-10-29
  • 1970-01-01
  • 2018-09-24
相关资源
最近更新 更多