2011-05-29 77 views
0

我有以下代码:为什么我的变量为空?

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

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

+0

正在使用超级(上下文),而不是超级(上下文,attrs)......感叹。谢谢您的帮助! – PearsonArtPhoto 2011-05-29 04:03:28