2016-01-30 135 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

相同的错误:/ –

相关问题