android - findViewById 在膨胀后在自定义 View 中返回 null

标签 android android-layout nullpointerexception android-custom-view layout-inflater

我有一个自定义的 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/

相关文章:

android - 从数据库中获取列表并在 Listview 中显示需要很长时间

安卓支持-v7 CardView : Header textview with other background color does not extend until the edges

android - 如何在启动画面中定位位图

Junit - 带有 @Before 的空指针异常

java - 在两个 Activity 之间切换而不丢失数据

java - Android 线程和电池生命周期

java - 更新 Android 中 CalendarView 中输入的日期

java - 我正在尝试使用 gui 制作一个三角形面积计算器,但是当我编译它时,我不断收到这个奇怪的错误

android - 如何在 webview 中禁用与 html5 视频的交互或正确捕获它们的异常?

android - distanceTo 返回的距离是多少?