2011-05-25 58 views
2

我想获得一个ImageView对象的引用,无论出于什么原因,它都会返回为null。Null ImageView参考

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); 

,我不觉得我做错了什么但我的IMG变种总是回来为空。这张照片有什么问题?

+2

是否v指的LinearLayout? – varuaa 2011-05-25 05:46:00

+0

添加您的日志和完整代码 – 2011-05-25 05:50:10

+0

你在哪里使用这个,你能告诉上下文 – 2011-05-25 06:09:20

回答

1

周六的答案是正确的,即您需要一个适当的布局,但setContentView()是不是唯一的方式来引用视图。您可以使用LayoutInflater来扩充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?) 

您需要将您的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> 
+1

好吧,我学到了不同的教训。我在一个ArrayAdapter类中使用了一个LayoutInflater。问题是当我调用inflate()时,我意外链接到错误的xml布局。我链接的布局恰好有一个TextView和CheckBox具有相同的ID,但没有ImageView。我的其他两个视图项目链接得很好,当ImageView没有时,它将我扔掉。我认为我要从中得到的东西是通用ID可能不是最好的想法,像“application_list_check”这样的描述性可能比“检查”更好,并为我节省了一些时间。 – HotN 2011-05-25 12:58:13

1

当您引用imageView时,请确保您使用的是正确的布局,即setContentView(R.layout.yourIntendedXmlLayout);

这个XML应该包含你的imageView。然后你可以参考你的imageView。

-1

使用

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