Sunday, March 24, 2019

Android Studio | Toast Messages

Toast Message





How to build toast messages in android.

Firstly create a project named as MyToastApp or you can name as you want.
Next > Finish project.

After creating our project we have two main files named as:-
  1. MainActivity.java.
  2. activity_main.xml.
Now Open up activity_main.xml file, copy and paste this below code:-

<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>

Open up MainActivity.java file and change the code as givien below:-

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button mMsgBtn = findViewById(R.id.mbtn);

        mMsgBtn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
             Toast.makeText(MainActivity.this, "I m Tony stark",Toast.LENGTH_LONG).show();
            }
        });
    }
}
Here, In android View is parent class of each component in android and Button is a subclass of the view parent class.

We have created a button class object as named mMsgBtn.

For click action, we need to set onClickListener to show a toast message.

mMsBtn.setOnClickListener(); //setting up the button listener.

Here, toast is class having its static methods (makeText()); and it has some of its method arguments like ( makeText(contex,"String message",Toast.Length_Short); ).
Context is the current application context on which message will be shown.

"String message" is some message what we wanted to display.

Toast.Length_Short and Toast.Length_Long is Time Duration how long we want to display the message on a screen, they both are the Toast class static variables.

Thank you for reading.. please subscribe to the channel or you can comment below :D.

No comments:

Post a Comment