我有一个习惯RelativeLayout
我在其中填充了一个 xml res 文件。
如果我在 xml 文件中使用自定义布局并将其设置为 contentview,则效果很好,但是如果我尝试将其添加到代码中new LocationItem(this)
and addChild()
the findViewById
方法总是返回null
在自定义的构造函数中RelativeLayout
.
这是代码:
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 中添加自定义视图
mRootLayoutLocations.addView(new LocationItem(this));
该视图正确膨胀,因为我可以看到它,但是当我尝试访问自定义视图内的视图时,应用程序崩溃并出现 NullPointerException。
好的,我将视图充气到视图(持有者)中
View v = inflate(getContext(), R.layout.list_item_location, this);
然后通过 v.findViewById 访问视图。现在它正在发挥作用。
Code:
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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)