简体   繁体   中英

Why is my variable null?

I have the following code:

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);
    }
}

The XML code looks like this (R.layout.level_layout) (Non-important stuff removed)

<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>

The log statement reads "score_bar=null".As you can see, there is a resource named R.id.Score_Bar. Am I missing something? I need to use the function for some other stuff. Thanks!

There are a number of things that can cause this. The most common being that for one reason or another R.id was not generated correctly. Usually doing a simple 'clean' will fix this. If that doesn't work another thing to check would be the constructor for the custom view. You can find this and other suggestions from this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM