-1

I am working on a custom toast and the code snippet is as show below i am inflating custom layout for this purpose where i need to set the layout parameters pragmatically,

 

Context context = getApplicationContext();
        // Create layout inflator object to inflate toast.xml file
        LayoutInflater inflater = getLayoutInflater();
          
        // Call toast.xml file for toast layout 
        View toastcreation = inflater.inflate(R.layout.toast, null);
          
        Toast toast = new Toast(context);
         
        // Set layout to toast 
        toast.setView(toastcreation );
       //how to set parameters programatically here??
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();

i need to make it center horizontal and cemter vertical. as also i am using toast.setDuration(Toast.LENGTH_LONG);, can time length explicitly be shown rather than using Toast.LENGTH_LONG

Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43
  • 1
    I have developed a custom Toast class with which you can show Toast for a specified amount of time... have a look at my answer... http://stackoverflow.com/questions/2220560/can-an-android-toast-be-longer-than-toast-length-long/21203554#21203554 – Gopal Gopi Feb 03 '14 at 04:39

2 Answers2

2

Use like this for your implementation:

LayoutInflater inflater = activity.getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast_layout, null);

    TextView text = (TextView) layout.findViewById(R.id.yourtext);
    text.setText(msg);

    Toast toast = new Toast(activity);
    toast.setGravity(Gravity.CENTER, 0, 40);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();

And use this set time for toast.

You can download the custom toast demo source code from here also : http://www.demoadda.com/demo/android/downlaod-demo-of-create-custom-toast-in-android-source-code_30

Community
  • 1
  • 1
Kishan Dhamat
  • 3,746
  • 2
  • 26
  • 36
1

In order to set the toast in the center you can use toast.setgravity method. Even if you specify a certain amount in place of length_long it would still take the default amount of time

Instead define a handler such that after an amount of time specified the handler would dismiss or cancel the toast.

Use handler.postDelayed method.

Hope that helps.