android 自定義控件View在Activity中使用findByViewId得到結果為null


轉載:http://blog.csdn.net/xiabing082/article/details/48781489

1.  大家常常自定義view,,然后在xml 中添加該view 組件。。如果在Activity 中使用findByViewId 方法獲取該view 時候,返回對象總為空 。。。
      xml 代碼
 
 
<com.infzm.slidingmenu.demo.view.CustomSurfaceView  
       android:id="@+id/customsufaceview"  
       android:layout_width="fill_parent"  
       android:layout_height="wrap_content"  
       android:layout_weight="6" />  
    java代碼
View rootView = View.inflate(this, R.layout.frag_shandina, null);  
        setContentView(rootView);  
setContentView(rootView);  
view = (CustomSurfaceView)findViewById(R.id.customsufaceview);  
LogUtils.i("blueberry", "view="+view);  
 
 打印結果總是為 null ,,  總是報空指針錯誤。。。
 
 其實問題還是出現在,,,自定義view 中,構造方法。。
 
解決方法:
 
錯誤寫法:
public CustomSurfaceView(Context context, AttributeSet attrs) {
super(context);
 
正確寫法:
public CustomSurfaceView(Context context, AttributeSet attrs) {  
//注意這里容易引起空指針異常的。。。。。  
super(context,attrs);  
這種初始化對象,會調用這個構造方法,,因為調用父類的構造函數沒有傳入AttributeSet ,
 
或者
CustomSurfaceView view = new CustomSurfaceView(this, null);
setContentView(view );
這種方式添加進行初始化。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM