我有一個自定義RelativeLayout
,我膨脹一個XML文件中的res文件。 這工作得很好,如果我在一個XML文件中使用自定義佈局,並將其設置爲內容查看,但如果我嘗試將其與new LocationItem(this)
和addChild()
添加在代碼中findViewById
方法總是在自定義RelativeLayout
的構造函數返回null
。findViewById在自定義視圖中返回null後膨脹
下面是代碼:
public class LocationItem extends RelativeLayout {
private String parcelType;
private int countIntoBox, countFromBox;
private RelativeLayout deliveryContainer, pickupContainer;
private TextView countPickup, countDelivery;
public LocationItem(Context context) {
this(context, null);
}
public LocationItem(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LocationItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
inflate(getContext(), R.layout.list_item_location, this);
deliveryContainer = (RelativeLayout) findViewById(R.id.rl_location_delivery_container);
pickupContainer = (RelativeLayout) findViewById(R.id.rl_location_pickup_container);
countPickup = (TextView) findViewById(R.id.tv_location_pickup_count);
countDelivery = (TextView) findViewById(R.id.tv_location_delivery_count);
countPickup.setOnClickListener(getShowNumberPickerListener());
countDelivery.setOnClickListener(getShowNumberPickerListener());
}
private OnClickListener getShowNumberPickerListener() {
return new OnClickListener() {
@Override
public void onClick(View view) {
showNumberPickerDialog(view);
}
};
} ...
}
添加自定義視圖在活動
mRootLayoutLocations.addView(new LocationItem(this));
的觀點是正確的膨脹,因爲我能看到它,但是當我試圖訪問內部的一個視圖使用NullPointerException自定義查看應用程序崩潰。
您的問題是mRootLayoutLocations爲空。這不在這個類的定義中。 – torque203
絕對不是! mRootLayoutLocations不爲null!此佈局位於我添加LocationItems的活動中:) – Fabian