user5474364
user5474364

Reputation:

Set Toast gravity top left in any textview android

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?

Upvotes: 2

Views: 1225

Answers (2)

Anirudh Sharma
Anirudh Sharma

Reputation: 7964

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.

Upvotes: 1

user5400869
user5400869

Reputation:

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();

Upvotes: 0

Related Questions