2011-05-25 46 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);