我有一个自定义的 RelativeLayout
并且我在其中扩充了一个 xml res 文件。
如果我在 xml 文件中使用自定义布局并将其设置为 contentview,则效果很好,但如果我尝试使用 new LocationItem(this)
和 addChild()< 将其添加到代码中
findViewById
方法总是在自定义 RelativeLayout
的构造函数中返回 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);
}
};
} ...
}
在 Activity 中添加自定义 View
mRootLayoutLocations.addView(new LocationItem(this));
View 已正确膨胀,因为我可以看到它,但是当我尝试访问自定义 View 内的 View 时,应用程序崩溃并出现 NullPointerException。
最佳答案
好的,我将 View 膨胀为 View (持有者)
View v = inflate(getContext(), R.layout.list_item_location, this);
然后通过 v.findViewById 访问 View 。现在它正在工作。
代码:
View v = inflate(getContext(), R.layout.list_item_location, this);
deliveryContainer = (RelativeLayout) v.findViewById(R.id.rl_location_delivery_container);
pickupContainer = (RelativeLayout) v.findViewById(R.id.rl_location_pickup_container);
countPickup = (TextView) v.findViewById(R.id.tv_location_pickup_count);
countDelivery = (TextView) v.findViewById(R.id.tv_location_delivery_count);
countPickup.setOnClickListener(getShowNumberPickerListener());
countDelivery.setOnClickListener(getShowNumberPickerListener());
关于android - findViewById 在膨胀后在自定义 View 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001062/