如何在屏幕中央显示吐司(How to display Toast at center of scre

2019-07-21 06:19发布

在Android中欲在屏幕的底部显示一个消息烤面包,我尝试这样做:

Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG).show();

它不工作,我怎么做是正确的?

Answer 1:

要在屏幕中央显示的吐司

Toast toast = Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();


Answer 2:

定位你的吐司

一个标准的吐司通知显示在靠近屏幕的底部,水平居中。 您可以更改与该位置setGravity(int, int, int)方法。 此接受三个参数:一个Gravity常数, x-position偏移,以及y-position偏移。

例如,如果你决定敬酒应出现在左上角,你可以这样设置的严重性:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

如果您想要的位置轻推到右侧,增加了第二个参数的值。 轻推下来,增加最后一个参数的值。



Answer 3:

自定义敬酒布局文件

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="5dp" />

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />

自定义敬酒java文件上按钮的单击事件

public class MainActivity extends Activity {

private Button button;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    button = (Button) findViewById(R.id.buttonToast);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // get your custom_toast.xml ayout
            LayoutInflater inflater = getLayoutInflater();

            View layout = inflater.inflate(R.layout.custom_toast,
              (ViewGroup) findViewById(R.id.custom_toast_layout_id));

            // set a dummy image
            ImageView image = (ImageView) layout.findViewById(R.id.image);
            image.setImageResource(R.drawable.ic_launcher);

            // set a message
            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText("Button is clicked!");

            // Toast...
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();
        }
    });
}

}



Answer 4:

Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.show();


Answer 5:

在Xamarin.Android,这将显示在烤面包屏幕中心:

            Toast toast = Toast.MakeText(ApplicationContext, "bbb", ToastLength.Long);
            toast.SetGravity(GravityFlags.Center, 0, 0);
            toast.Show();


Answer 6:

下面的代码为我工作。

Toast.makeText(this, "Toast in center", Toast.LENGTH_SHORT).setGravity(Gravity.CENTER,0,0).show();


文章来源: How to display Toast at center of screen