title: Android Testing: Inflate and Display a custom Toast from Instrumentation
body: <p>I am trying to display a custom Toast but doing so from my automated test rather than from the application itself. </p>
  
  <p>The layout inflation does not work though. Is it even possible to inflate views and from the test project and display those? </p>
  
  <p>What does work is a standard Toast:</p>
  
  <pre><code>final Activity targetActivity = Solo.getCurrentActivity(); // Using Robotium to get current displayed Activity
  Toast.makeText(targetActivity, "Hello from Instrumentation", Toast.LENGTH_SHORT).show();
  </code></pre>
  
  <p>What does NOT work is the following:</p>
  
  <pre><code>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();
  </code></pre>
  
  <hr>
  
  <p><strong>Solution</strong></p>
  
  <p>Get new <code>LayoutInflater</code> without reference to <code>targetActivity</code></p>
  
  <pre><code>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();
  </code></pre>