我开始使用ButterKnife并且我得到它正在片段中使用膨胀的视图。
但我有一个问题,是否有可能获得不夸大的观点?
例如,我的MainActivity中有一个工具栏,但不在片段内。我可以使用ButterKnife访问此工具栏吗?
等问题。我尝试使用以下方法获取工具栏高度:
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
int toolbarHeight = toolbar.getHeight();
但是这个返回始终为0.如何直接从视图中获取工具栏大小? 现在我正在使用:
getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValueToolbarHeight, true);
但实际上我想从视图中获取工具栏。
答案 0 :(得分: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);
} });