4

У меня есть пользовательский RelativeLayout, и я раздуваю файл res xml в нем. Это прекрасно работает, если я использую пользовательский макет в xml-файле и устанавливаю его как contentview, но если я попытаюсь добавить его в код с new LocationItem(this) и addChild(), метод findViewById всегда возвращает null в конструкторе пользовательского RelativeLayout.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.

+0

Ваша проблема заключается в том, что mRootLayoutLocations равна нулю. Это не в определении этого класса. – torque203

+0

Не определенно нет! mRootLayoutLocations не равно нулю! Этот макет находится в действии, где я добавляю LocationItems :) – Fabian

ответ

0

Вам необходимо использовать соответствующие конструкторы, не перегружая их.

public class LocationItem extends RelativeLayout { 

    private String parcelType; 
    private int countIntoBox, countFromBox; 

    private RelativeLayout deliveryContainer, pickupContainer; 

    private TextView countPickup, countDelivery; 

    public LocationItem(Context context) { 
     super(context); 
     init(context, null, 0); 
    } 

    public LocationItem(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context, attrs, 0); 
    } 

    public LocationItem(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(context, attrs, defStyle); 
    } 

    private void init(Context context, AttributeSet attrs, int 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); 
      } 
     }; 
    } 

    ... 
} 
+0

То же самое. Все еще исключение NullPointerException. – Fabian

+1

Опубликовать трассировку стека, пожалуйста ... также вы устанавливаете требуемое поле ширины и высоты в коде? :) –

+2

Хорошо, я раздул вид на вид (держатель) Посмотреть v = надуть (getContext(), R.layout.list_item_location, это); , а затем получить доступ к представлениям через v.findViewById. Теперь он работает. Может быть, вид не привязан к корневому представлению так быстро? – Fabian

0

Я боюсь, что вы должны раздуть вид, а не находить его из ниоткуда. Метод

findindViewById(int Id) 

должен быть вызван в OnCreate в Actvity или с целью, в течение которого вид ребенка/виджет вы пытаетесь найти это пребывает в.

Если все представления детей проживает в одном XML-файл (в пределах одного родительского корня)

View rootView=(View) LayoutInflater.from(context).inflate(R.layout.list_item_location); 
pickupContainer = (RelativeLayout) rootview.findViewById(R.id.rl_location_pickup_container); 
+1

Да, это то, что я сделал - см. Комментарии ниже. – Fabian

0

это должно работать

public LocationItem(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    this = inflate(getContext(), R.layout.list_item_location,null); 
    ... 
2

Хорошо я завысил вид в виде (держатель)

View v = inflate(getContext(), R.layout.list_item_location, this); 

, а затем получить доступ мнения через v.findViewById. Теперь он работает.

Код:

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()); 
Смежные вопросы