0

Below is my code, this closes the app as I have set the image in my class. What seems wrong with this? Easier way to load the image?

public static class FiveSkills extends Activity{
    ImageView img = (ImageView) findViewById(R.id.img);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image);
        img.setImageResource(R.drawable.five_skills);
    }
}

XML Layout

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="59dp"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="15dp"
    android:text="Five Skills"
    android:textColor="#08088A"
    android:textAppearance="?android:attr/textAppearanceLarge" />

4

2 回答 2

3

The issue here is that by the time you are using the method, findViewById(R.id.img), your views might not even been inflated yet, in order for the code to work get areference to the image after setContentView is called, something like this:

ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image);
    img = (ImageView) findViewById(R.id.img);
    img.setImageResource(R.drawable.five_skills);
}

Hop this helps.

Regards!

于 2013-08-05T18:54:49.363 回答
1

获得子视图的最佳方法是一旦它的父级被夸大。这是你得到的唯一原因"ANR"

似乎您混淆了Java在类旁边抓取变量的概念并使其成为全局。完全正确,这就是我们一贯的做法。但是当涉及到从XML Layout文件中获取视图时。你需要给它充气,这发生在Activityunder的开头onCreate()。最好看看你正在处理的事情的生命周期。所以去谷歌搜索Life Cycle of Activity仅供参考。

您的代码看起来像这样:

public static class FiveSkills extends Activity
{
   protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image);
    ImageView img = (ImageView) findViewById(R.id.img); // Inflate child view once your parentview is available.
    img.setImageResource(R.drawable.five_skills);
   }
}  

获得布局文件后,您将在Activity. 之后,您就可以下拉布局子视图了。

于 2013-08-05T18:58:49.137 回答