2016-01-30 76 views
0

我有一個ImageView的,不具有酶活性的佈局:我可以在課堂上設置佈局嗎? (無活性)

pieza.xml

<?xml version="1.0" encoding="utf-8"?> 
<ImageView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/image" 
    android:src="@drawable/arribin" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
/> 

和在另一方面,我有一個類,其中我嘗試修改佈局膨脹:

public void init(){ 
    res = this.getContext().getApplicationContext().getResources(); 
    lInf = (LayoutInflater)(getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)); 
    lInf.inflate(R.layout.game, this, true); 
} 

private int getPieceId(){ 
    //trying to set the image 
    ImageView image=(ImageView)findViewById(R.id.image); 
    image.setImageResource(R.drawable.fast); 
    return R.layout.pieza; 
} 
... 
View newPiece = lInf.inflate(getPieceId(), null); 

而且logcat的:

ImageView.setImageResource(INT)」上空對象引用

我可以在沒有Activity的情況下設置佈局的ImageView嗎?

回答

0

上述代碼的問題在於image ImageView是null。你應該修改init()方法是

View view = lInf.inflate(R.layout.game, this, true); 

然後找到ImageView如下:

ImageView image = (ImageView) view.findViewById(R.id.image); 

編輯 好了,既然你提到了,我想你pieza.xml包含image ImageView的。 修改代碼如下,並檢查

View newPiece = lInf.inflate(R.layout.pieza, null); 
ImageView image = (ImageView) newPiece.findViewById(R.id.image); 
image.setImageResource(R.drawable.fast); 

您可以發表評論的getPieceId()方法。你不需要它。

+0

我認爲這些不是問題(只是試過了,它不起作用)。 R.layout.game是活動的佈局,並且工作正常。我認爲問題是pieza.xml沒有活動。無論如何謝謝 –

+0

檢查我編輯的答案。 – Antrromet

+0

logcat返回相同的:( –

0

每個佈局資源文件應該有佈局類型。 似乎pieza.xml沒有任何特定的佈局類型(RelativeLayout,LinearLayout等...)。

因此,當您膨脹pieza.xml時,它將導致null。

嘗試在開始的pieza.xml中使用LayoutType作爲ImageView的父級,它應該可能工作。 希望它可以幫助...

編輯:

似乎ü使用R.layout.game膨脹的觀點....

嘗試在pieza.xml插入ImageView的到game.xml ...它不會顯示nullpointerException ...

原因是,findViewById()的作品只能找到當前設置佈局的引用,即你不能只參考視圖是充氣佈局的孩子我認爲。

+0

相同的錯誤:/ –

相關問題