Remove icon from Toast (Android 12) [duplicate] - android

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.

Related

Xamarin.Forms FindViewById() Returns null

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:

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.

Glow button on and off

I have two images which I want to fade between causing a glowing on and off effect. This should run all the time like an animation, not just when the button is pressed.
Here are the two images:
This was working well before but after some hardware/android OS updates my animation is really jumpy. Here is the Animation XML I was using:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/bottom_bar_add_dark"/>
<item android:drawable="#drawable/bottom_bar_add" android:duration="500" />
</animation-list>
I have looked high and low and cannot find an answer to this.
Edit
Here is the code that creates the image view and sets all its resources:
public ImageView findDevicesButton(){
bottomButton = new ImageView(this);
int id = bottomButton.generateViewId();
bottomButton.setId(id);
if(currentapiVersion >= 11){
bottomButton.setImageResource(R.drawable.animationxmladddevice);
//Background image
bottomButton.setBackgroundResource(R.drawable.bottom_bar);
saveButtonAnimation = (AnimationDrawable)bottomButton.getDrawable();
saveButtonAnimation.setEnterFadeDuration(1000);
saveButtonAnimation.setExitFadeDuration(1000);
bottomButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
findDevicesAlertBuilder();
}
});
}else{
bottomButton.setImageResource(R.drawable.bottom_bar_add);
bottomButton.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bottomButton.setBackgroundResource(R.drawable.bottom_bar);
bottomButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
findDevicesAlertBuilder();
}
});
}
return bottomButton;
}
This is the back background image:
All together it should look like this with the center button glowing:

Is it possible to create a clickable Toast-like notification?

I have a need to show a minimally-intrusive non-blocking notification which is not tied to the activity it was shown in (like a Toast) and which is clickable. Anyone have any idea whether or not this is possible? Unfortunately, it appears that Toast notifications (custom or otherwise) are not clickable (i.e. setting an OnClickListener on its views has no effect). All the alternatives that I'm aware of (i.e. AlertDialog, PopupWindow and Crouton) seem to show a notification which is tied to the activity it was shown in (i.e. they won't continue showing when the activity finishes). Any suggestions?
You can use PopupWindow, add an onClickListener and add a handler to auto cancel it after n times (just like the behavior of a toast). Something like this:
public static void showToast(Activity a, String title, String message) {
// inflate your xml layout
LayoutInflater inflater = a.getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) a.findViewById(R.id.toast_layout_root));
// set the custom display
((TextView) layout.findViewById(R.id.title)).setText(title);
((TextView) layout.findViewById(R.id.message)).setText(message);
// initialize your popupWindow and use your custom layout as the view
final PopupWindow pw = new PopupWindow(layout,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, true);
// set windowType to TYPE_TOAST (requires API 23 above)
// this will make popupWindow still appear even the activity was closed
pw.setWindowLayoutType(WindowManager.LayoutParams.TYPE_TOAST);
pw.showAtLocation(layout, Gravity.CENTER | Gravity.TOP, 0, 500);
// handle popupWindow click event
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do anything when popupWindow was clicked
pw.dismiss(); // dismiss the window
}
});
// dismiss the popup window after 3sec
new Handler().postDelayed(new Runnable() {
public void run() {
pw.dismiss();
}
}, 3000);
}
xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toast_layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:elevation="10dp"
android:padding="20dp">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFF"
android:textStyle="bold"/>
<TextView
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFF"/>
</LinearLayout>
You are right, a Toast object has no way to be interacted with, but there are many libraries out there that will give you the same look and feel as a toast, but with some interactivity. The one I use is https://github.com/JohnPersano/SuperToasts
I think what you need is in fact a PopupWindowwhich can be seen here "http://developer.android.com/reference/android/widget/PopupWindow.html".
Toasts have a very specific task, which is to inform the user, without any input from them. So instead of trying to extend the purpose of the Toast, use the PopupWindow which can be interacted with by the user.
A 'Dialog' type of activity will probably be your best bet.
In manifest:
<activity android:name=".ToastLikeActivity"
android:theme="#android:style/Theme.Dialog"
android:label="#string/label"
></activity>
And timeout the activity within the onCreate():
class ToastLikeActivity extends Activity {
#Override
public void onCreate(Bundle state)
// auto-kill activity after X seconds <-------------------------
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
ToastLikeActivity.this.finish(); // kill after X seconds
}
}
}, VisibleTimeSecs*1000);
}
To display the dialog start it as with any other activity:
Intent i = new Intent(this, ToastLikeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
And it will show up and automatically go away after X seconds.
Such a popup will not be tied to the caller activity. In fact - it will not even require a caller activity. You
can activate it (bad idea, but possible) even from a service.
You can implement basically any kind of sensitive (i.e. accepting user's clicks) interface you want to
the ToastLikeActivity. Especially: you can make its exteriors transparent, giving it a dialog-likke looks.

Android Dialog like WeChat

Has anyone know how to create a dialogbox like the picture showing above?
Rounded corner.
Transparent background.
No title, buttons, border.
Fade-in -- delay for 5 seconds -- fade out.
*I have seen toast, popup window, dialog, alert dialog, which of these best suit the above? :)
It would be nice if some code snippet could be provided, I'm fairly new to android :)
For custom dialog check http://www.c-sharpcorner.com/UploadFile/2fd686/androd-dialogs/
private void createCustomDialog(){
//Create a dialog object
final Dialog dialog = new Dialog(MainActivity.this);
//Set its layout
dialog.setContentView(R.layout.custom_dialog_layout);
//Set the title
dialog.setTitle("This is custom layout");
//Make it cancelable
dialog.setCancelable(true);
//We need to dismiss the dialog so we add a listener to the ok button
dialog.findViewById(R.id.okButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
}
For the dark alpha background you can create a drawable. Below code will give you a semi transparent background with round corners.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle">
<gradient
android:startColor="#AA000000"
android:endColor="#AA000000"
android:angle="-90"
android:type="linear"
/>
<corners android:radius="10dp" />
</shape>
</item>
</layer-list>
For the auto hide part you can use
Animation anim = new AlphaAnimation(1,0);
anim.setDuration(300);
anim.setStartOffset(5000);
anim.setInterpolator(new LinearInterpolator());
anim.setFillAfter(false);
myView.startAnimation(anim);
It is not a problem at all. Just create 9nth patch drawable with delays and fading and put it as bg for the dialog.
Try this
Create XML with with your desired Content and then set transparent image to that
I am providing you image, use this
and the
Declare field of type PopupWindow.
PopupWindow popup;
inflate your layout here
View v = inflatter.inflate(R.layout.yourlayout, null);
set your layout to the popup window
v1.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int height1 = v1.getMeasuredHeight();
popup= new PopupWindow(v, (int) (width * 0.8), height1, true);
popup.showAtLocation(mainlayout, Gravity.CENTER, 0, 0);
mainlayout is your activity view group
this is the piece of code that I have used in my app.
Example I have used something like this in my app
Custom Toast would do everything for you, just prepare your xml and set it to Toast, here is a sample:
public class CustomToast {
public CustomToast(Context ctx, CharSequence text) {
LayoutInflater inflater = LayoutInflater.from(ctx);
View layout = inflater.inflate(R.layout.toast_layout, null);
TextView txt = (TextView) layout.findViewById(R.id.toastText);
txt.setText(text);
Toast myToast = new Toast(ctx.getApplicationContext());
myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);
myToast.setDuration(Toast.LENGTH_SHORT);
myToast.setView(layout);
myToast.show();
}
}

Categories

Resources