import android.widget.Toast
import android.view.Gravity
默认Toast是显示在底部的,可以通过以下方法让其显示在顶部正中
Toast toast = Toast.makeText(SearchActivity.this, "取消关注失败", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0); toast.show();
这样设置会使Toast在中间弹出
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void upperLeft(View v) { Toast toast = Toast.makeText(this, "Upper Left!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); toast.show(); } public void upperRight(View v) { Toast toast = Toast.makeText(this, "Upper Right!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0); toast.show(); } public void bottomLeft(View v) { Toast toast = Toast.makeText(this, "Bottom Left!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0); toast.show(); } public void bottomRight(View v) { Toast toast = Toast.makeText(this, "Bottom Right!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); toast.show(); }
默认Toast是显示在底部的,可以通过以下方法让其显示在顶部正中
Toast mToast = Toast.makeText(
this,
R.string.correct_toast,
Toast.LENGTH_SHORT
)
mToast.setGravity(Gravity.TOP,0,0)
mToast.show()
#顶部,水平居中
Toast toast= Toast.makeText(getApplicationContext(),
"Your string here", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
通过以下方法让其显示在右上角:
private int getScreenWidth() {
DisplayMetrics outMetrics = new DisplayMetrics();
windowManager.defaultDisplay.getMetrics(outMetrics);
Log.i("width", outMetrics.toString());
return outMetrics.widthPixels;
}
mToast.setGravity(Gravity.TOP, getScreenWidth()/2, 0);
#底部 右边
Toast toast = Toast.makeText(this, "Custom toast creation", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
toast.show();
refs:https://blog.csdn.net/xuanshao_/article/details/106502177
标签:Toast,setGravity,show,toast,Gravity,LENGTH,Android From: https://www.cnblogs.com/bluestorm/p/18216182