Android Toast.Set Gravity Causing App To Crash - android

I don't understand why my toast is crashing the app.
I have two sets of code, the one I originally did which is crashing and one that I found that is working.
The one the is working creates the toast object and declares the text at the same time.
Toast toast =
Toast.makeText(QuizActivity.this,R.string.incorrect_toast, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
The one I made creates the object in the context, sets the text then the gravity and tries to show it.
Toast toast = new Toast(QuizActivity.this);
toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Why is this crashing my app?

Your
Toast toast = new Toast(QuizActivity.this);
constructs an empty Toast object. You must call setView(View) before you can call show().
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.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
as it stated in Android docs.

you can try this
Toast toast = Toast.makeText(QuizActivity.this,"your string", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

You can create a toast object like this.
Toast toast = new Toast(QuizActivity.this);
This line of code construct an empty Toast object.
Then you have to call the setView() , setDuration() on your own. makeText() method is a static method. So, you can't call it from a toast object.
You can initialize a Toast object by calling the method makeText() method.
For this reason, the first code is working properly and the second is not.

This is crashing because you are not called setView() method before calling show mehod.
Calling constructor(Toast toast = new Toast(QuizActivity.this);) will construct an empty Toast object.This object will not contain a default view to show,So you have to call setView() method to set a view for the toast.Then only this will work.

Most probably you are getting RuntimeException.
'java.lang.RuntimeException: setView must have been called'
You are just creating an instance of Toast uisng "new Toast(QuizActivity.this)" and you did not set any view for it. You have to set your own custom layout to Toast.
SOLUTION:
LayoutInflater inflate = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Custom layout
View view = inflate.inflate(R.layout.custom_toast, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText("Hello world!");
// Toast
Toast toast = new Toast(QuizActivity.this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
// Set the Toast custom layout
toast.setView(view);
toast.show();
Here is custom_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="5px"
android:padding="10dp"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"
android:layout_width="50dp"
android:layout_height="50dp"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="Android Tutorial Custom Toast"
android:textColor="#fff"
android:textSize="16dp"
android:layout_gravity="center_vertical"/>
</LinearLayout>
</LinearLayout>
Hope this will help~

Related

Issue with custom Toast with color

I trying to make a custom toast with the background "Orange color", however, in the attempt I am able to get it but the field also becomes white and the text is not visible, I have attached the image
You can see that the text is not visible.
here is my code:
String g= "+";
Toast toast = Toast.makeText(getActivity(), "Click and hold on '"+g+"' icon",
Toast.LENGTH_SHORT);
View view= toast.getView();
view.setBackgroundColor(Color.parseColor("#FF791B"));
View t = toast.getView().findViewById(android.R.id.message);
t.setBackgroundColor(Color.parseColor("#FFFFFF"));
toast.show();
I just want the text to be in white.
Is something I am missing in the code, I am not able to get it right.
Also, is there a way to make the "+" sign bold g
Just Change this line
t.setBackgroundColor(Color.parseColor("#FFFFFF"));
To
t.setTextColor(Color.parseColor("#FFFFFF"));
I have mode some changes here:
TextView t = toast.getView().findViewById(android.R.id.message);
t.setTextColor(Color.WHITE);
I have saved it as textView and I was able to get the setTextColor method and I was able to change the color
Try this - customttoast.xml is your custom toast xml and custom_toast_layout can be your activity layout xml
//Creating the LayoutInflater instance
LayoutInflater li = getLayoutInflater();
//Getting the View object as defined in the customtoast.xml file
View layout = li.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.id.custom_toast_layout));
//Creating the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);//setting the view of custom toast layout
toast.show();

Show lengthy content of a textview as a toast message android

I have a TextView and it contains lengthy contents. These textview are readonly and no scrolling provided. So that entire text cannot be seen in the textview. Now I want to show a toast message in the longClick event. But the toast message is shown in the bottom of the screen. How can I show it just below the selected TextView?
final Toast viewToast = Toast.makeText(getActivity(), packageId.getText().toString(), Toast.LENGTH_LONG);
packageId.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
viewToast.show();
return false;
}
});`
You can show the Toast at different location by using this method:
customToast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
For custom location please go through this URL
For custom position please go through this link
How can I show it just below the selected TextView?
To show Toast below of TextView or any View use Toast.setGravity method with X and Y offsets:
int coordinates[] = new int[2];
textView.getLocationInWindow(coordinates);
int xOffset=coordinates[0]+getWidth()/2;
int yOffset=coordinates[1]+ getHeight;
viewToast.setGravity(Gravity.TOP|Gravity.LEFT,xOffset,yOffset);
viewToast.show();
Change position of Toast on Activity Window using xOffset and yOffset according to your requirement.
Try make your toast custom,
<ImageView android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp" />
<TextView android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF" />
Java code
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layouts));
ImageView image = (ImageView) layout.findViewById(R.id.image1);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text1);
text.setText("Type your long message here");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Create a Toast that Comes From Top of Screen

I am wondering how do we create a Custom toast in Android that shows on the top of screen like this?
I came from iOS background and now I have to create custom controls like this.
Any pointers please?
Thank you
Check this link: https://github.com/gfranks/GFMinimalNotifications, this is what you want i think and it is working fine for me.
output:
Or you can prepare custom toast like this:
View layout = getLayoutInflater().inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 0);
toast.setView(layout);
toast.show();
you can use crouton for this purpose.
Description :
A Crouton will be displayed at the position the developer decides.
Standard will be the top of an application window. You can line up
multiple Croutons for display, that will be shown one after another
Create a Crouton for any CharSequence:
Crouton.makeText(Activity, CharSequence, Style).show();
more details on Crouton, a Context sensitive notifications for Android
there are many you can use for toast describe here
try this ::
Toast toast= Toast.makeText(getApplicationContext(),
"Your string here", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
add this line for position
toast.setGravity(Gravity.TOP, 0, 0);
creat customize toast layout, toast.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/yellow"
android:layout_width="match_parent"
android:padding="8dp"
android:gravity="center"
android:textSize="32sp"
android:layout_height="256dp"/>
create toast using the layout above:
static Toast t;
public static void show(Context c, String s) {
if (t == null) {
t = new Toast(c.getApplicationContext());
t.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
LayoutInflater inflater = LayoutInflater.from(c);
TextView v = (TextView) inflater.inflate(R.layout.toast, null);
t.setView(v);
t.setDuration(Toast.LENGTH_LONG);
}
TextView v = (TextView) t.getView();
v.setText(s);
t.show();
}
As you can see, there are many solutions. But the easiest way is create a layout in your XML layout file, and make it invisible. When this view needs to be shown make it visible and start an animation.

Custom toast inflate root meaning

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
This is a lines of creating custom toast (from: http://developer.android.com/guide/topics/ui/notifiers/toasts.html)
It works fine, but I don't know why use the code
(ViewGroup) findViewById(R.id.toast_layout_root)
I think findViewById method runs find view "present" element,
so that method returns null,
That means, meaningless code, doesn't it?
Why I wonder that problem is I try to use create custom toast in Service
Service has not findViewById, you know,
so I just try to inflate(id, null) that lead to my layout broken,
I already read http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ article.
How can I inflate properly without my layout parameter loss information

Android: How to set the colour of a Toast's text

I am displaying a toast message as the result of an if statement using the following code:
Toast.makeText(getBaseContext(), "Please Enter Price", Toast.LENGTH_SHORT).show();
It is displayed as white text on a white background, as such it can not be read! My question is, how can I change the colour of the toast's text?
You can achieve this very easily, without creating a custom layout by modifying the default Toast :
Toast toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.RED);
toast.show();
You can find the layout used by the default toast view in the Android SDK :
$ANDROID-SDK$/platforms/android-8/data/res/layout/transient_notification.xml
You can create a custom Toast view to suit your requirements. See the section titled "Creating a Custom Toast View" at http://developer.android.com/guide/topics/ui/notifiers/toasts.html
You may want to create a custom Toast
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
-
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! This is a custom toast!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Source
The simplest way to change the background color of a toast and the background color of a toast's text:
View view;
TextView text;
Toast toast;
toast.makeText(this, resId, Toast.LENGTH_SHORT);
view = toast.getView();
text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.black));
text.setShadowLayer(0,0,0,0);
view.setBackgroundResource(R.color.white);
toast.show();
Try to use Toasty library. It is really easy to use it - https://github.com/GrenderG/Toasty
You can also use SpannableString. It can also color parts of the string.
SpannableString spannableString = new SpannableString("This is red text");
spannableString.setSpan(
new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)),
0,
spannableString.length(),
0);
Toast.makeText(this, spannableString, Toast.LENGTH_SHORT).show();
You can try this if you don't wish to use any custom libraries
Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
View view=toast.getView();
TextView view1=(TextView)view.findViewById(android.R.id.message);
view1.setTextColor(Color.YELLOW);
view.setBackgroundResource(R.color.colorPrimary);
toast.show();
Here is an example in Kotlin, showing how you can change the background color of a toast and it's text color :
val toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
toast.view.background.setColorFilter(ContextCompat.getColor(context,
R.color.white), PorterDuff.Mode.SRC_IN)
val textView = toast.view.findViewById(android.R.id.message) as TextView
textView.setTextColor(ContextCompat.getColor(context, R.color.black))
toast.show()
The solution with setting a custom view on Toast is deprecated for API 30 and forward.
Documentation says
apps
* targeting API level {#link Build.VERSION_CODES#R} or higher that are in the background
* will not have custom toast views displayed.
The alternative is
Toast.makeText(applicationContext,
HtmlCompat.fromHtml("<font color='red'>custom toast message</font>", HtmlCompat.FROM_HTML_MODE_LEGACY),
Toast.LENGTH_LONG).show()
Html color tag can also be <font color='#ff6347'>
For every modification that has to do with the text displayed the above solution would be enough. You can for example make the text bold by inserting <b>my text</b> or you maybe want to change the font-familywith <font font-family='...'> my text </font> For all those changes that solution will be enough.
If you want to modify the container though with properties like background-color the only alternative is to use Snackbar. View can not be modified for Toast anymore.
https://developer.android.com/guide/topics/ui/notifiers/toasts?hl=es-419#java
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Categories

Resources