【问题标题】:How to be sure that all views got created如何确保创建了所有视图
【发布时间】:2013-06-06 10:06:42
【问题描述】:

我正在使用AsyncTask,并且在我创建的其中一个后台线程中,我必须知道给定View 的大小。 但有时这种观点还没有被创造出来。 所以问题是:在 Activity 生命周期的哪个部分,我可以确定所有视图都已经到位并且定义了维度?

PS:我的代码在Fragment 中,我已经尝试过onResume() 方法。

【问题讨论】:

    标签: android android-layout android-fragments android-asynctask android-view


    【解决方案1】:

    自定义您想要获取大小的视图:

    public class SizeFetchableView extends YourView{
    
    //constructors...
    
    private SizeFetchListener mSizeFetchListener;
    public void setSizeFetchListener(SizeFetchListener l){
           mSizeFetchListener = l;
    }
    public void onLayout(boolean isChanged,int l,int t,int r,int b){
           super.onLayout(l,t,r,b);
           if(mSizeFetchListener!=null){
             mSizeFetchListener.onFetchSize(this,isChanged,getWith(),getHeight());
           }
    }
    
    public interface SizeFetchListener{
    public void onFetchSize(View view,boolean isChanged,int w,int h);
    }
    
    }
    

    所以,您可以在第一时间使用 SizeFetchListener 获取视图大小,但是您的线程逻辑依赖于大小,必须等待获取大小接口调用。

    public class Task extends Thread implements SizeFetchListener{
    SizeFetchableView mSizeFetchableView;
       public Task(SizeFetchableView v){
              mSizeFetchableView=v;
              mSizeFetchableView.setSizeFetchListner(this);
       }
    
       public void onFetchSize(View view,boolean isChanged,int w,int h){
       //and this time ,you can start you thread if not,or continue you logic who waiting the size
    
       }
    }
    

    //请原谅我的英语不好。谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多