довольно долго я пытался решить проблему с помощью Null Pointer Exception при заполнении ViewStub. То, что я пытаюсь сделать, находится в SlidingDrawer, который содержит некоторые кнопки изображения и ViewStubs, чтобы заполнить ViewStubs при нажатии кнопки ImageButton. Я наблюдаю за Обзор класса ViewStub для создания ViewStubs, но я все равно получаю исключение Null Pointer. Если бы кто-то мог помочь мне здесь, это было бы здорово, потому что я действительно больше не знаю, что я должен сделать, чтобы решить эту проблему... Я отправлю свой код ниже
Спасибо вам заблаговременно!
Вот часть моего кода, вызывающая исключение:
btnExposure = (ImageButton) findViewById(R.id.button_exposure);
btnExposure.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
try{
ViewStub stub = (ViewStub) findViewById(R.id.stub_exposure);
importStub = stub.inflate();
}catch (Exception e){
Log.e("ERROR", "Error in Code:" +e.toString());}
}
});
Это XML файл DrawingSlider, содержащий ViewStub:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/shape_background_gradient"
>
<LinearLayout
android:layout_width="205px"
android:layout_height="155px"
android:background="#FFCCCCCC"
android:id="@+id/VideoViewHolder"
android:padding="2.5px"
android:layout_centerHorizontal="true"
android:layout_marginTop="5px"
android:layout_marginBottom="5px"
>
<VideoView
android:layout_width="200px"
android:layout_height="150px"
android:id ="@+id/VideoViewEdit"
android:layout_centerHorizontal="true"
>
</VideoView>
</LinearLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/VideoViewHolder">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0">
<TableRow
android:background="@drawable/shape_track_background"
android:padding="5px"
>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_editor_videotrack"
android:padding="5px"
android:layout_gravity="left"/>
</TableRow>
<TableRow
android:background="@drawable/shape_track_background"
android:padding="5px"
>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_editor_audiotrack"
android:padding="5px"
android:layout_gravity="left"/>
</TableRow>
<TableRow
android:background="@drawable/shape_track_background"
android:padding="5px"
>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_editor_add_media"
android:padding="5px"
android:layout_gravity="left"
/>
</TableRow>
</TableLayout>
</ScrollView>
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:handle="@+id/handle"
android:content="@+id/content">
<ImageView
android:id="@id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/slider_handle"
/>
<LinearLayout
android:id="@id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageButton
android:id="@+id/button_exposure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#77000000"
android:src="@drawable/ic_slider_exposure"
android:padding="5px"
android:layout_marginBottom="1px"
android:layout_gravity="left"/>
<ImageButton
android:id="@+id/button_properties"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#77000000"
android:src="@drawable/ic_slider_properties"
android:padding="5px"
android:layout_marginBottom="1px"
android:layout_gravity="left"/>
<ImageButton
android:id="@+id/button_special_effects"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#77000000"
android:src="@drawable/ic_slider_special_effects"
android:padding="5px"
android:layout_marginBottom="1px"
android:layout_gravity="left"/>
<ImageButton
android:id="@+id/button_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#77000000"
android:src="@drawable/ic_slider_exposure"
android:padding="5px"
android:layout_marginBottom="1px"
android:layout_gravity="left"/>
<ImageButton
android:id="@+id/button_test2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#77000000"
android:src="@drawable/ic_slider_exposure"
android:padding="5px"
android:layout_marginBottom="1px"
android:layout_gravity="left"/>
</LinearLayout>
<ViewStub
android:id="@+id/stub_exposure"
android:inflatedId="@+id/stub_exposure_view"
android:layout="@layout/exposureview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#77000000">
</ViewStub>
<ViewStub
android:id="@+id/stub_properties"
android:inflatedId="@+id/stub_properties_view"
android:layout="@layout/propertiesview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#77000000">
</ViewStub>
<ViewStub
android:id="@+id/stub_special_effects"
android:inflatedId="@+id/stub_special_effects_view"
android:layout="@layout/specialeffectsview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#77000000">
</ViewStub>
</SlidingDrawer>
</RelativeLayout>
И это макет ViewStub xml (exposureview.xml), который вызывается для раздувания заглушки:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+String/hello"
></TextView>
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/seek_thumb"
android:progress="50"
android:max="100">
</SeekBar>
</RelativeLayout>
По-видимому findViewById(R.id.stub_exposure);
возвращает null для вас. Вы правильно перекомпилировали свой класс, чтобы восстановить файл R.java?
Кроме того, я заметил, что вы определили одно из текстовых свойств текстового представления в своем XML файле макета stub layout как android:text="@+String/hello"
.
Не знаю, была ли это опечатка или нет, но правильно ли был создан R.java
? Если у вас есть существующее значение в strings.xml
(обратите внимание на не верхний регистр), компилятор должен подать жалобу.
Вы должны попытаться выполнить проект → Очистить, чтобы узнать, получаете ли вы предупреждения или ошибки (если вы используете Eclipse).
stub_exposure
в сгенерированном R.java
?
Раздувание или отображение ViewStub приводит к его удалению из макета (вся его точка должна быть заменена другим видом). Ваш метод onClick будет работать только в первый раз. Вы должны (a) проверить нуль, возвращаемый из findViewById, и (b) использовать идентификатор вида, который вы надуваете в заглушку после инфляции.
Как подозревает JRL, это связано с тем, что findViewById(R.id.stub_exposure)
не находит/видит/улавливает stub_exposure
, хотя идентификатор был хорошо сгенерирован в R.class
, а затем метод возвращает null
и когда inflate()
называется ничего не происходит, потому что stub
все еще не инициализирован, это всего лишь объект null
. Вы можете увидеть это, используя отладчик.
Итак, следовательно, мы видим, что, возможно, есть какая-то проблема с синтаксическим анализатором или компилятором XML. Я решил проблему, поставив View
для использования StubView
из одного выделенного файла XML в файл XML, где у меня был основной интерфейс с более Layout
и View
s. Я положил его в первый родительский Layer
, который был LinearLayout
, но мне пришлось вставить его в FrameLayout
вместе с моим StubView
, чтобы все теги Layer
отображались одинаково. Я думаю, что это должно быть важно, потому что у вас также есть StubView
внутри Layer
, но он не работает на вас. Поэтому постарайтесь поставить StubView
на разные уровни иерархии.
importStub = stub.inflate();