findViewById inside a Static Method

TheLettuceMaster picture TheLettuceMaster · May 2, 2013 · Viewed 14.9k times · Source

I have this static method:

public static void displayLevelUp(int level, Context context) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.custom_level_coast,
            (ViewGroup) findViewById(R.id.toast_layout_root));  // this row

    TextView text = (TextView) layout.findViewById(R.id.toastText);
    text.setText("This is a custom toast");

    Toast toast = new Toast(context);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();

    Toast.makeText(context, String.valueOf(level), Toast.LENGTH_SHORT)
            .show();

}

However, I can't figure out how to get the firstfindViewById to play nice with this as it says it is a non-static method. I understand why it says that, but there must be a workaround? I passed context into this method but couldn't work them out together.

Answer

tyczj picture tyczj · May 2, 2013

One thing you can do is make the view a class wide variable and use that. I dont actually recommend doing that but it will work if you need something quick and dirty.

Passing in the view as a parameter would be the preferred way