I’m trying to get a reference to an ImageView object and for whatever reason, it keeps coming back as null.
XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip">
<ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:text="Application Name" />
<CheckBox android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" />
</LinearLayout>
Java:
ImageView img = (ImageView) v.findViewById(R.id.application_icon);
I don’t feel like I’m doing anything wrong yet my img var always comes back as null. What’s wrong with this picture?
Sat’s answer is correct, i.e., you need a proper layout, but
setContentView()is not the only way to reference a View. You can use aLayoutInflaterto inflate a parent layout of theView(even if it is not shown) and use that newly inflated layout to reference the View.The only change you need to your xml file is to add an ID to the parent layout, so you can use it with the
LayoutInflater: