I am trying to display a custom Toast but doing so from my automated test rather than from the application itself.
The layout inflation does not work though. Is it even possible to inflate views and from the test project and display those?
What does work is a standard Toast:
final Activity targetActivity = Solo.getCurrentActivity(); // Using Robotium to get current displayed Activity
Toast.makeText(targetActivity, "Hello from Instrumentation", Toast.LENGTH_SHORT).show();
What does NOT work is the following:
final Activity targetActivity = Solo.getCurrentActivity(); // Using Robotium to get current displayed Activity
LayoutInflater inflater = targetActivity.getLayoutInflater();
View layout = inflater.inflate(test.my.package.R.layout.my_custom_toast, null); // resource is located in test project
TextView text = (TextView) layout.findViewById(test.my.package.R.id.textToShow); // textview within the layout
text.setText("Hello from Instrumentation"); // here I get the NullPointerException
Toast toast = new Toast(targetActivity);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Solution
Get new LayoutInflater
without reference to targetActivity
final Activity targetActivity = Solo.getCurrentActivity(); // Using Robotium to get current displayed Activity
// *** !!! ***
LayoutInflater inflater =
(LayoutInflater) getInstrumentation().getContext().getSystemService (Context.LAYOUT_INFLATER_SERVICE);
// getContext() , NOT getTargetContext()
View layout = inflater.inflate(test.my.package.R.layout.my_custom_toast, null); // resource is located in test project
TextView text = (TextView) layout.findViewById(test.my.package.R.id.textToShow); // textview within the layout
text.setText("Hello from Instrumentation"); // here I get the NullPointerException
Toast toast = new Toast(targetActivity);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();