سؤال

Back Story

I am setting a background programmatically so I do the following in onCreate, and it works fine.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dogs);
    Drawable bkg = getResources().getDrawable(R.drawable.bg2);
    bkg.setAlpha(50);
    findViewById(R.id.bkg).setBackgroundDrawable(bkg);
    ...
}

Problem

Needing to repeat the same process for multiple activities, I decide to extract the code into a helper class call MyVars and inside MyVars I have

private static Drawable bkg = null;

public static void setPageBackground(Context context, View view) {
    if (null == bkg) {
        Drawable bkg = context.getResources().getDrawable(R.drawable.bg2);
        bkg.setAlpha(50);
    }
    view.setBackgroundDrawable(bkg);
}

Then inside onCreate I now have

MyVars.setPageBackground(this, findViewById(R.id.bkg));

but then bkg is always null, which means context.getResources().getDrawable(R.drawable.bg2); always returns null. Does anyone understand why? By the way, I run the debugger and indeed the resource always returns null.

هل كانت مفيدة؟

المحلول

bkg is always null because you assign the drawable to a method field bkg not to the class field bkg:

Change your method to this

public static void setPageBackground(Context context, View view) {
    if (null == bkg) {
        //Drawable bkg = getResources().getDrawable(R.drawable.bg2);

        //use class field bkg
        bkg = context.getResources().getDrawable(R.drawable.bg2);
        bkg.setAlpha(50);
    }
    view.setBackgroundDrawable(bkg);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top