Skip to content Skip to sidebar Skip to footer

Android Testing: Inflate And Display A Custom Toast From Instrumentation

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 t

Solution 1:

Hi Use the below codes:

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.R;

publicclassDoToastextendsToast {

    /** The Constant TOAST_DURATION. */privatestaticfinalint TOAST_DURATION=4000;

    /** The layout. */
    View layout; 

    /**
     * Instantiates a new do toast.
     *
     * @param context the context
     * @param text the text
     */publicDoToast(Context context, CharSequence text) {
        super(context);

        LayoutInflaterinflater= (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.toast, null);
        TextViewtextView= (TextView) layout.findViewById(R.id.text);
        textView.setText(text);
        DoToast.this.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        DoToast.this.setDuration(TOAST_DURATION);
        DoToast.this.setView(layout);
        DoToast.this.show();
    }
}

Layout xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/toast_layout_root"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="wrap_content"android:padding="8dp"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:background="@drawable/toast_bg"><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="5dp"android:textColor="#000000" /></LinearLayout>

And Style file:

<?xml version="1.0" encoding="utf-8"?><shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle" ><gradientandroid:angle="90"android:endColor="#ffffff"android:startColor="#F2F2F2"android:type="linear" /><strokeandroid:width="3dp"android:color="#000000" /></shape>

If you need to show toast then just use the below line:

newDoToast(this,"Testing");  

Let me know if you have any queries..

Solution 2:

I believe the issue is to do with the context, you are trying to show a toast from your test applications R files but using the applications context via an activity, what you will want to do is get the test context from instrumentation and then create a layout inflater from that using the following.

Contextcontext= instrumentation.getContext();
 LayoutInflaterli= LayoutInflater.from(context);

Post a Comment for "Android Testing: Inflate And Display A Custom Toast From Instrumentation"