#java #android
Вопрос:
Я пытаюсь дотянуться до кнопки, которая находится в макете под названием task_item.xml
, но мне это не удалось.
Часть моего кода:
View inflatedView = getLayoutInflater().inflate(R.layout.task_item, null);
private Button deleteButton;
deleteButton = (Button) inflatedView.findViewById(R.id.delete_button);
deleteButton.setVisibility(View.VISIBLE);
Я получаю NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.view.Window.getLayoutInflater()' on a null object reference
Комментарии:
1. Возможно, с помощью приложения Context LayoutInflater
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
2. Я использую ваш инфлатер знаю так: « LayoutInflater инфлатер = (LayoutInflater) getApplicationContext().getSystemService( Контекст. LAYOUT_INFLATER_SERVICE ); Просмотр inflatedView = inflater.inflate(R. layout.task_item, null); ` «Но я получаю ту же ошибку: `» Попытка вызвать виртуальный метод » android.content. Контекст android.контент. Context.getApplicationContext()’ по нулевой ссылке на объект«
3. Вы не надуваете перед
onCreate()
методом?, если да, то надувайте послеonCreate()
метода.
Ответ №1:
Попробуйте этот код:
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);
View inflatedView = layoutInflaterAndroid.inflate(R.layout.task_item, null);
private Button deleteButton;
deleteButton = (Button) inflatedView.findViewById(R.id.delete_button);
deleteButton.setVisibility(View.VISIBLE);
Убедитесь, что R.id.delete_button
кнопка находится внутри R.layout.task_item
макета.
Убедитесь, что вы внимательно передаете контекст. Например, имя активности.это. Это происходит, когда контекст равен нулю.