为什么我的变量为null?

时间:2011-05-29 03:12:46

标签: android android-layout

我有以下代码:

public class Level extends Activity{

    public static String TAG="Level";

    Level_Score_bar score_bar;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.level_layout);

        score_bar=(Level_Score_bar) findViewById(R.id.Score_Bar);
        Log.d(TAG,"score_bar="+score_bar);
    }
}

XML代码看起来像这样(R.layout.level_layout)(删除了非重要的东西)

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical">
    <pearsonartphoto.AJEG.Level_Score_bar android:id="@+id/Score_Bar" android:layout_height="wrap_content" android:layout_width="fill_parent">
    </pearsonartphoto.AJEG.Level_Score_bar>
</LinearLayout>

日志语句显示为“score_bar = null”。如您所见,有一个名为R.id.Score_Bar的资源。我错过了什么吗?我需要将这个功能用于其他一些东西。谢谢!

1 个答案:

答案 0 :(得分:1)

有很多事情可以导致这种情况。最常见的原因是由于某种原因R.id未正确生成。通常做一个简单的'干净'将解决这个问题。如果这不起作用,另一件要检查的是自定义视图的构造函数。您可以从this question找到此建议和其他建议。

相关问题