プロジェクト名:CustomToast
Toastの表示位置を変更するコード。
通常何も指定せずにToastを表示した場合、画面の下部にToastの吹き出しが表示される。
画面にキーボードが表示されていると下部のToastは見にくいため、Toastの表示位置を変更したい場合。
残念ながらAndroid 11以降はsetGravityでの位置調整ができなくなりました。下の方にだけ表示されるようになった。


以下の「onClick」設定は、直接「activity_main.xml」14行目のように記述しても良い。

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="48dp"
android:onClick="button1_click"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.29"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="button1_click"
android:text="@string/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.281"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.042" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.customtoast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu; //追加
import android.view.*; //追加
import android.widget.*; //追加
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//--以下を追加--//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void button1_click(View view){
Toast.makeText(this, "テストメッセージ", Toast.LENGTH_LONG).show();
}
//--以下を追加--//
}
上のスクリプトで以下のようにボタンを押すと下の方にメッセージが表示される。

位置調整ができなくなったらしい。
以下のようにすると下から上の付近になるというがならない。これが使えなくなったらしい。
ts.setGravity(Gravity.TOP, 0, 160);