2

I want to set my toast message at top|left position in any text view of my application so I used this code

public class CustomToast extends Activity {

TextView mTextView1;
TextView mTextView2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_toast);
      mTextView1=(TextView)findViewById(R.id.textView);
      mTextView2=(TextView)findViewById(R.id.textView2);
    mTextView1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCustomAlert( );
        }
    });
    mTextView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCustomAlert( );
        }
    });
}
public void showCustomAlert( )
{

    Context context = getApplicationContext();
    // Create layout inflator object to inflate toast.xml file
    LayoutInflater inflater = getLayoutInflater();

    // Call toast.xml file for toast layout
    View toastRoot = inflater.inflate(R.layout.toast, null);

    Toast toast = new Toast(context);

    // Set layout to toast
    toast.setView(toastRoot);
    toast.setGravity(Gravity.TOP|Gravity.LEFT ,0, 0);
    toast.setDuration(2000);
    toast.show();

  }
}

When I run above code, toast displays at top of screen every time not in particular textview see image below.

Initially two text view screen

enter image description here

When I click on second textview I get this toast position

enter image description here

Any idea how can I solve this issue?

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
  • You cannot put the Toast like custom view in xml with visibility gone ? & then when you want to show the toast setvisibility to View.Visible with the required text ? – Syed Nazar Muhammad Oct 22 '15 at 05:30

2 Answers2

1

All you need to do is manage the Toast position according the position of textview on your screen.Then you need to dynamically add the coordinates of view every time to your Toast.So you need to get the coordinates of the view that is clicked using:

buttonView.getLocationOnScreen(location);

Then set the position of Toast:

toast.setGravity(Gravity.TOP|Gravity.LEFT,buttonView.getRight()+5, 
location[1]-10);

The above is only a reference.For more clear and descriptive idea please see This and This.

Community
  • 1
  • 1
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
0

Use the Below code :

Toast toast= Toast.makeText(getApplicationContext(), 
"Your string here", Toast.LENGTH_SHORT);  
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();