問題:使用findviewById() 返回空,直到初始化控件的時候才報空指針異常。
今天寫android自定義控件的時候突然發現了一個問題,也不報錯,實在蛋疼。後面發現是因爲自定義控件構造函數使用不對,
自定義構造函數有三個構造函數。
Class(Context); 普通構造函數,無法加載屬性集(無法加載XML文件中定義的控件屬性,導致無法從XML文件中
始 化)。
Class(Context,Attribute); 帶屬性集的構造函數,可以加載屬性集(同時也可以加載XML文件中定義的屬性)。
Class(Context,Attribute,int); 帶屬性集和默認風格的構造函數。
- 附上XML佈局與代碼:
1、XML佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg2" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<com.todayfocus.view.BannerFlipper
android:id="@+id/banner_fliper"
android:layout_width="match_parent"
android:layout_height="150dp" >
</com.todayfocus.view.BannerFlipper>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:background="@android:color/darker_gray"
android:text=" " />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
>
<com.todayfocus.view.SubGridLayout
android:id="@+id/grid_subscription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:columnCount="3" >
</com.todayfocus.view.SubGridLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
2、 代碼:
public class BannerFlipper extends ViewFlipper implements DataSetObserver{
private Context mContext;
private MyBaseAdapter mAdapter;
private AttributeSet mAttrs;
private int mNum = 0;
public BannerFlipper(Context context){ //問題就處在這裏,該構造函數沒有屬性參數,無法加載XML控件的參數,因此無法初始化。
super(context);
mContext = context;
}
@Override
public void onChanged() {
mNum = mAdapter.getCount();
update();
}
public void setAdapter(MyBaseAdapter adapter){
mAdapter = adapter;
mAdapter.registerObserver(this);
}
private void update(){
this.removeAllViews();
for (int i = 0; i < mNum; i++) {
RelativeLayout item = (RelativeLayout) mAdapter.getView(i);
this.addView(item);
}
}
}
在初始化的時候:
protected void findViews() {
mBannerFlipper = (BannerFlipper) mView.findViewById(R.id.banner_fliper);//該處返回空指針,之後初始化報空指針異常
mGridLayout = (SubGridLayout) mView.findViewById(R.id.grid_subscription);
}
後面多次調試之後,才發現是因爲控件的構造函數中沒有參數,因此無法加載XML文件裏面的屬性用來初始化。
問題就在於,自定義控件如果要在XML裏面加載,就需要構造函數中有AttributeSet參數用來加載XML屬性。