Android 空ImageView引用

Android 空ImageView引用,android,xml,android-layout,imageview,Android,Xml,Android Layout,Imageview,我试图获取一个对ImageView对象的引用,不管出于什么原因,它总是返回空值 XML: 我不觉得我做错了什么,但我的img var总是返回为null。这张图片有什么问题?在引用imageView时,请确保使用了正确的布局,即setContentView(R.layout.YourIntentendXMLLayout) 该xml应该包含您的imageView。然后您可以参考您的imageView。使用 ImageView img=(ImageView)findviewbyd(R.id.appli

我试图获取一个对ImageView对象的引用,不管出于什么原因,它总是返回空值

XML:


我不觉得我做错了什么,但我的img var总是返回为null。这张图片有什么问题?

在引用imageView时,请确保使用了正确的布局,即setContentView(R.layout.YourIntentendXMLLayout)

该xml应该包含您的imageView。然后您可以参考您的imageView。

使用


ImageView img=(ImageView)findviewbyd(R.id.application_图标)

Sat的答案是正确的,即您需要一个适当的布局,但是
setContentView()
并不是引用视图的唯一方法。您可以使用展开视图的父布局(即使未显示),并使用新展开的布局引用视图

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?)
您需要对xml文件进行的唯一更改是向父布局添加一个ID,以便您可以将其与
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>


v指的是线性布局吗?你在哪里使用这个,你能告诉上下文吗?好的,我学到了另一个教训。我在ArrayAdapter类中使用LayoutFlater。问题是,在调用inflate()时,我意外地链接到了错误的xml布局。我链接到的布局恰好有一个TextView和复选框,ID相同,但没有ImageView。我的其他两个视图项链接得很好,当ImageView没有链接时,这让我很失望。我想我要从中吸取的是,通用ID可能不是最好的主意,一些更具描述性的东西,如“应用程序列表检查”可能比“检查”更好,并为我节省了一些时间。
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?)
<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>