2011-05-29 88 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