qui*_*tor 22 android android-view
在片段中,我使用多个子视图为一个布局充气.我需要获得其中一个的尺寸(宽度和高度),这是一个自定义视图.
在自定义视图类中,我可以轻松完成.但是如果我尝试从片段中做到这一点,我总是得到0作为维度.
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
View culoide = view.findViewWithTag(DRAW_AREA_TAG);
Log.d("event", "culoide is: "+culoide.getWidth()); // always 0
}
Run Code Online (Sandbox Code Playgroud)
我认为onViewCreated应该是获得它的正确位置,但这种情况发生了.我在super.onViewCreated之前尝试过,在调试它看起来像'findViewWithTag'找到了正确的视图,仅尝试使用api 7 v4支持.
有帮助吗?
Kar*_*uri 41
你必须等到为了得到非零值的第一项措施和布局后getWidth()和getHeight().你可以用一个ViewTreeObserver.OnGlobalLayouListener
public void onViewCreated(final View view, Bundle saved) {
super.onViewCreated(view, saved);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// get width and height of the view
}
});
}
Run Code Online (Sandbox Code Playgroud)
我首选的方法是向OnLayoutChangeListener要跟踪自己的视图添加一个
CustomView customView = ...
customView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// Make changes
}
});
Run Code Online (Sandbox Code Playgroud)
如果只需要初始布局,则可以在回调中删除侦听器.
| 归档时间: |
|
| 查看次数: |
18227 次 |
| 最近记录: |