Hello,
I'm Corinne, and I'm self-taught at Android Studio.
I set the gravity on the toast message as below, but the button pops up and the message doesn't pop upㅠ<
If you change AMD from Nexus 5 something to Pixel something, a toast message appears, but it doesn't show up with the set gravity ㅠ<
I don't know what the problem is Masters, please teach me ㅠ<
package org.techtown.toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast = Toast.makeText(getApplicationContext(), "Toast changed location", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.LEFT,200,200);
toast.show();
}
});
}
}
If you check the setGravity document in the toast class, it says that it does not work for simple text toast while targeting version R or higher.
I think you can use the toast with a custom view.
Below is a snippet with a simple custom view.
// MainActivity.java
findViewById(R.id.main_button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP|Gravity.LEFT,200,200);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
<LinearLayout
<!-- custom_toast.xml -->
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:background="#DAAA"
>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="TOAST"
/>
</LinearLayout>
© 2024 OneMinuteCode. All rights reserved.