And*_*cko 3 android android-layout android-lifecycle android-fragments android-view
我有一个片段,我需要在屏幕上测量其视图的位置/宽度/高度,并传递给其他类.
所以我所拥有的是一个功能,它是这样的:
private void measureTest(){
v = ourView.findViewById(R.id.someTextField);
v.getLocationOnScreen(loc);
int w = v.getWidth();
...
SomeClass.passLocation(loc,w);
...
Run Code Online (Sandbox Code Playgroud)
问题是视图的位置/宽度/高度在片段生命周期内没有准备好.所以,如果我在这些生命周期方法中运行该函数:
onCreateView
onViewCreated
onStart
onResume
Run Code Online (Sandbox Code Playgroud)
我要么得到错误的位置和宽度/高度测量值或0值.我找到的唯一解决方案是GlobalLayoutListener向mainView 添加这样的解决方案
mainView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
if(alreadyMeasured)
mainView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
else
measureTest();
}
});
Run Code Online (Sandbox Code Playgroud)
这可以完成工作..但它只是Yack!IMO.
有没有更好的方法呢?看起来像是一件基本的事情
onActivityCreated片段内部检索currentView(with getView())并将runnable发布到其队列中.在runnable调用内部measureTest()
| 归档时间: |
|
| 查看次数: |
2653 次 |
| 最近记录: |