1. 程式人生 > >androidの自定義控制元件View在Activity中使用findByViewId得到結果為null,解決方法。。

androidの自定義控制元件View在Activity中使用findByViewId得到結果為null,解決方法。。

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

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 );
這種方式新增進行初始化。。 更多詳情自定義view 方法解決見: