WoodPecker
WoodPecker

Reputation: 19

Change the Toast display position

I want to change Toast display postion, and i use setGravity(Gravity.CENTER,0,0); But i found it doesn't work. It displays like the default(at the bottom of screen). Where is the proplem? Thanks.

Here is my java code

public class ToastViewActivity extends AppCompatActivity {

    private Button mBtnToast1,mBtnToast2,mBtnToast3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast_view);
        setTitle("Learn ToastView");
        mBtnToast1 = findViewById(R.id.btn_toast_1);
        mBtnToast2 = findViewById(R.id.btn_toast_2);
        mBtnToast3 = findViewById(R.id.btn_toast_3);
        OnClick onClick = new OnClick();
        mBtnToast1.setOnClickListener(onClick);
        mBtnToast2.setOnClickListener(onClick);
        mBtnToast3.setOnClickListener(onClick);
    }

    class OnClick implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_toast_1 :
                    Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
                    break;
                case R.id.btn_toast_2 :
                    Toast toastCenter = Toast.makeText(ToastViewActivity.this,"CENTER",Toast.LENGTH_LONG);
                    toastCenter.setGravity(Gravity.CENTER,0,0);
                    toastCenter.show();
                    break;
                case R.id.btn_toast_3 :
                    break;
            }
        }
    }
}

Upvotes: 0

Views: 598

Answers (1)

Henry Twist
Henry Twist

Reputation: 5980

Unfortunately setting Toast gravity is no longer supported. If you take a look at the documentation it specifically says:

Warning: Starting from Android Build.VERSION_CODES#R, for apps targeting API level Build.VERSION_CODES#R or higher, this method is a no-op when called on text toasts.


To get the required behaviour you would have to implement a custom solution.

Upvotes: 1

Related Questions