Null ImageView Reference

99封情书 提交于 2020-01-04 17:21:58

问题


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?


回答1:


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 a LayoutInflater to inflate a parent layout of the View (even if it is not shown) and use that newly inflated layout to reference the View.

public class MyActivity extends Activity {
  Context context;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
// the rest of yout code

private void someCallback() {
  LayoutInflater inflater = (LayoutInflater) context.getSystemService
     (Context.LAYOUT_INFLATER_SERVICE);
  LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.iconLayout, null);
  ImageView img = (ImageView) ll.findViewById(R.id.application_icon);
// you can do whatever you need with the img (get the Bitmap, maybe?)

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:

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="iconLayout"
<!-- all the rest of your layout -->
  <ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<!-- all the rest of your layout -->
</LinearLayout>



回答2:


When you are referencing the imageView , make sure that you are using the proper layout, i.e. setContentView(R.layout.yourIntendedXmlLayout);

That xml should contain your imageView. Then you can refer to your imageView.




回答3:


use

ImageView img = (ImageView)findViewById(R.id.application_icon);



来源:https://stackoverflow.com/questions/6120004/null-imageview-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!