Xamarin.Forms FindViewById() Returns null - android

I am trying to create a toast with a custom font, in my layout file in the android project i did:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/toastTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:fontFamily="#font/made_evolve_sans_light"
android:textColor ="#424242"
android:textSize="25sp"
/>
</LinearLayout>
And then for the custom toast I did:
Toast toast = Toast.MakeText(Application.Context, message, ToastLength.Long);
TextView v = (TextView)toast.View.FindViewById(Resource.Id.toastTextView);
v.SetTextSize(Android.Util.ComplexUnitType.Sp, 25);
toast.View.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#F2e3dace"), PorterDuff.Mode.SrcIn);
toast.SetGravity(GravityFlags.Center, 0, 0);
toast.Show();
But then at runtime, the textview v is always null.
How do I find my textview with my custom font by its ID?
THank you!

as far as i know the textview id from toast is: android.R.id.message

From your description, you want to create Toast with custom font in Xamarin.forms, you can use DependencyService to get it.
In your Share code project, create interface toast:
public interface toast
{
void Show(string message);
}
Then implement this interface in Android platform. you can use following code to create custom font Toast.Don't forget to register the platform implementations.
[assembly: Xamarin.Forms.Dependency(typeof(Toast_Android))]
namespace FormsSample.Droid
{
public class Toast_Android : toast
{
public void Show(string message)
{
Toast toast = Toast.MakeText(Application.Context, message, ToastLength.Long);
TextView v = (TextView)toast.View.FindViewById(Android.Resource.Id.Message);
v.SetTextSize(Android.Util.ComplexUnitType.Sp, 25);
toast.View.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#F2e3dace"), PorterDuff.Mode.SrcIn);
var typeface = Typeface.Create("customfont", Android.Graphics.TypefaceStyle.Bold);
v.Typeface = typeface;
toast.SetGravity(GravityFlags.Center, 0, 0);
toast.Show();
}
}
}
For Android native platform, there is one textview from Toast: Android.Resource.Id.Message
Then you can get Toast by Button.click method:
private void btn2_Clicked(object sender, EventArgs e)
{
DependencyService.Get<toast>().Show("Toast Message");
}
The screenshot:

Related

Remove icon from Toast (Android 12) [duplicate]

I just installed the Android R (API 30) image in my emulator to try my app, and it crashed when trying to set the Background color of a Toast.
Toast toast = Toast.makeText(ctxt, msg, duration);
View view = toast.getView();
view.setBackgroundColor(0xFF303030);
TextView tview = view.findViewById(android.R.id.message);
tview.setTextColor(Color.WHITE);
toast.show();
This is really strange as in Android Q (API 29) works perfectly.
My build.gradle updated for Android R (API 30)
compileSdkVersion 30
buildToolsVersion "30.0.1"
Is there a new way to do it??
Since Android 11, custom toasts/ toast modifications are deprecated, according to Google to "protect users". Hence why your app in Android 30 is not able to display custom toasts.
From Android Developers documentation:
Custom toast views are deprecated. Apps can create a standard text toast with the makeText(android.content.Context, java.lang.CharSequence, int)
The only way I have found of showing custom toasts from API 30 onwards is by creating them ad hoc.
XML LAYOUT
Customize as needed
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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=".main_activity">
<!--Ad hoc toast Textview-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:layout_margin="18dp"
android:background="#drawable/ad_hoc_toast_background"
android:textColor="#1e1e1e"
android:gravity="center"
android:visibility="gone"
android:layout_alignParentBottom="true"
android:id="#+id/ad_hoc_toast_textview"
tools:text="Temporary message bla bla bla ..."/>
</RelativeLayout>
TOAST BACKGROUND (ad_hoc_toast_background.xml)
Customize as needed
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="220dp"
android:height="100dp"/>
<corners
android:radius="25dp"
/>
<solid
android:color="#e6ffffff"
/>
</shape>
</item>
</selector>
Define the show_ad_hoc_toast() method
private void show_ad_hoc_toast(final TextView ad_hoc_toast_textview, String text){
//Set the text
ad_hoc_toast_textview.setText(text);
//Create alpha animation
AlphaAnimation animation1 = new AlphaAnimation(0f, 1f);
//Set duration
animation1.setDuration(300);
//Set that the animation changes persist once the animation finishes
animation1.setFillAfter(true);
//Set on AnimationEnd Listner
animation1.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation){}
#Override public void onAnimationRepeat(Animation animation){}
#Override public void onAnimationEnd(Animation animation){
//After 2250 millis -> hide the toast
new CountDownTimer(2250, 1) {
public void onTick(long millisUntilFinished){}
public void onFinish() {hide_ad_hoc_toast(ad_hoc_toast_textview);}
}.start();
}
});
//Make the view visible
ad_hoc_toast_textview.setVisibility(View.VISIBLE);
//Start animation
ad_hoc_toast_textview.startAnimation(animation1);
}
Define the hide_ad_hoc_toast() method
private void hide_ad_hoc_toast(final TextView ad_hoc_toast_textview){
//Create alpha animation
AlphaAnimation animation1 = new AlphaAnimation(1f, 0f);
//Set duration
animation1.setDuration(300);
//Set that the animation changes persist once the animation finishes
animation1.setFillAfter(true);
//Set on AnimationEnd Listner
animation1.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) { }
#Override public void onAnimationRepeat(Animation animation) { }
#Override public void onAnimationEnd(Animation animation) {
//Make the view gone
ad_hoc_toast_textview.setVisibility(View.GONE);
}
});
//Start animation
ad_hoc_toast_textview.startAnimation(animation1);
}
Call the method from your code when needed
//Find ad_hoc_toast textview
TextView ad_hoc_toast_textview = findViewById(R.id.ad_hoc_toast_textview);
//Define the text to be shown
String text = "This is the custom toast message"
//Show the ad_hoc toast
show_ad_hoc_toast(ad_hoc_toast_textview, text);
RESULT
You can check before to custumized toast
Toast toast = Toast.makeText(ctxt, msg, duration);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
View view = toast.getView();
view.setBackgroundColor(0xFF303030);
TextView tview = view.findViewById(android.R.id.message);
tview.setTextColor(Color.WHITE);
}
toast.show();
#pvalle & #Aayush Panda, It works for me in Android 11. Please check below code
public static void showCenterToastMessage(Context context, String msg) {
LayoutInflater inflater = LayoutInflater.from(context);
View layout = inflater.inflate(R.layout.custom_toast,null);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(msg);
text.setPadding(20,0,20,0);
text.setTextSize(18);
text.setTextColor(Color.WHITE);
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
layout.setBackgroundColor(Color.DKGRAY);
toast.setView(layout);
toast.show();
}
layout is as follows
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
The solution with setting a custom view on Toast is deprecated for API level 30
Documentation says
This method was deprecated in API level 30. Custom toast views are
deprecated. Apps can create a standard text toast with the
makeText(android.content.Context, java.lang.CharSequence, int) method,
or use a Snackbar when in the foreground. Starting from Android
Build.VERSION_CODES#R, apps targeting API level Build.VERSION_CODES#R
or higher that are in the background will not have custom toast views
displayed.
There is a walkaround though which still works and is not deprecated
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'>
WindowManager interface can be an alternative to the toast after the Android 11 limitations.
https://developer.android.com/reference/android/view/WindowManager
But you just need user permission to display custom messages over the apps.

Android Toast.Set Gravity Causing App To Crash

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~

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.

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