Sctep 1. Create layout xml with activity_main.xml
Step 2. Create class MainActivity.java
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#bdc7ca"
>
<Button
android:id="@+id/btn_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top Toast"
/>
<Button
android:id="@+id/btn_bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bottom Toast"
android:layout_below="@id/btn_top"
/>
<Button
android:id="@+id/btn_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left Toast"
android:layout_below="@id/btn_bottom"
/>
<Button
android:id="@+id/btn_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right Toast"
android:layout_below="@id/btn_left"
/>
<Button
android:id="@+id/btn_center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Center Toast"
android:layout_toRightOf="@id/btn_top"
/>
</RelativeLayout>
public class MainActivity extends Activity {Result :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
Button btn_top = (Button) findViewById(R.id.btn_top);
Button btn_bottom = (Button) findViewById(R.id.btn_bottom);
Button btn_right = (Button) findViewById(R.id.btn_right);
Button btn_left = (Button) findViewById(R.id.btn_left);
Button btn_center = (Button) findViewById(R.id.btn_center);
final Toast toast = Toast.makeText(
getApplicationContext(), // Context
"Simple Toast", // Message
Toast.LENGTH_SHORT // Short Duration
);
btn_top.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.setGravity(Gravity.TOP,0,10);
toast.setText("Toast Position Top");
toast.show();
}
});
btn_bottom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.setGravity(Gravity.BOTTOM,0,10);
toast.setText("Toast Position Bottom");
toast.show();
}
});
btn_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.setGravity(Gravity.RIGHT,10,0);
toast.setText("Toast Position Right");
toast.show();
}
});
btn_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.setGravity(Gravity.LEFT,10,0);
toast.setText("Toast Position Left");
toast.show();
}
});
btn_center.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
toast.setText("Toast Position Center");
toast.show();
}
});
}
}