Sunday, March 24, 2019

Making a custom toast message in android app

Custom toast message.



In this example, we are going to make some custom toast message while clicking a button.
Making a custom toast message is very simple and easy. just follow the below steps.

As we made a simple toast message earlier, we have used a toast class object and calling the method
makeText so this method is used to generate toast text messages. If we want to show up any custom view like any layout resource or an image toast, then we have to instantiate toast class for classing a method setView.

Step1:- Open up your MainActivity.java file, copy and paste the below code.

ImageView imageView;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

       imageView = new ImageView(this);
       imageView.setImageResource(R.drawable.images);

    Button mMsgBtn = findViewById(R.id.mbtn);
    mMsgBtn.setOnClickListener(new View.OnClickListener() {
        @Override        public void onClick(View v) {
            Toast toast = new Toast(getApplicationContext());
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.setView(imageView);
            toast.show();
        }
    });
}
Step2:- Open up your activity_main.xml layout file, copy and paste it.

<LinearLayout 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"    android:orientation="vertical"    tools:context=".MainActivity">

    <Button        android:layout_gravity="center"        android:text="Show message"        android:id="@+id/mbtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />

</LinearLayout>

As you can see we made an ImageView object for showing an image toast message.ImageView or any view in android must have a constructor with argument context. So, we passed the current application context inside ImageView constructor.

For setting any image in ImageView there is a method called setImageResource.
You need to have an image inside your app > res > drawable folder. Just copy the image anywhere from your pc and paste inside this drawable folder. Remember to have an image name in lowercase because android studio only supports the files named in lowercase.

Toast object is using the setGravity method to set the toast position as the center you can change it as
Gravity.BOTTOM, Gravity.TOP or Gravity.LEFT and Gravity.RIGHT.

No comments:

Post a Comment