how to show the toast on the top of the activity in android studio code example
Example 1: android studio make toast appear at top of screen
Toast toast = Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Example 2: android studio make toast appear at top of screen
private void displayToastAboveButton(View v, int messageId)
{
int xOffset = 0;
int yOffset = 0;
Rect gvr = new Rect();
View parent = (View) v.getParent();
int parentHeight = parent.getHeight();
if (v.getGlobalVisibleRect(gvr))
{
View root = v.getRootView();
int halfWidth = root.getRight() / 2;
int halfHeight = root.getBottom() / 2;
int parentCenterX = ((gvr.right - gvr.left) / 2) + gvr.left;
int parentCenterY = ((gvr.bottom - gvr.top) / 2) + gvr.top;
if (parentCenterY <= halfHeight)
{
yOffset = -(halfHeight - parentCenterY) - parentHeight;
}
else
{
yOffset = (parentCenterY - halfHeight) - parentHeight;
}
if (parentCenterX < halfWidth)
{
xOffset = -(halfWidth - parentCenterX);
}
if (parentCenterX >= halfWidth)
{
xOffset = parentCenterX - halfWidth;
}
}
Toast toast = Toast.makeText(getActivity(), messageId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, xOffset, yOffset);
toast.show();
}