1

我开始使用 ButterKnife 并且我知道它在片段内部工作,并且视图被夸大了。

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

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

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

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

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

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

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

4

1 回答 1

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); 
    } });
于 2015-02-15T05:43:54.217 回答