FindViewById inside a static method

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 cannot figure out how to get the first findViewById to play with this well, as it says it is a non-static method. I understand why this says, but there should be a workaround? I passed context to this method, but could not parse them.

+6
source share
3 answers

One thing you can do is make a representation of the class variable and use it. I really do not recommend doing this, but it will work if you need something quick and dirty.

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

+6
source

It's a bit strange. But you can pass the root view as a parameter.

 //some method... ViewGroup root = (ViewGroup) findViewById(R.id.toast_layout_root); displayLevelUp(level, context, root); //some method end... public void displayLevelUp(int level, Context context, ViewGroup root) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_level_coast, root); 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(); } 
+2
source

If you want to stick with the static method, use Activity instead of Context as a parameter and execute Activity.findViewById like this:

 public static void displayLevelUp(int level, Activity activity) { LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.toastText, (ViewGroup) activity.findViewById(R.id.abs__action_bar_container)); // this row 

Another way to do this is to pass the parent ViewGroup as a parameter instead of Context or Action:

 public static void displayLevelUp(int level, ViewGroup rootLayout) { View layout = rootLayout.inflate(rootLayout.getContext(), R.layout.custom_level_coast, rootLayout.findViewById(R.id.toast_layout_root)); // this row 
+1
source

Source: https://habr.com/ru/post/944133/


All Articles