Here you can add a project name and location for that project and click the Next button then another window will appear and you can select the Minimum SDK that you want to create. And then in the next window, you can select the template you like from a list of predefined templates and click Finish.
Now your project will be created in Android Studio. And you will have some folders like res, src, manifest like that these are the files needed for Android application. In which your java files will be in the src folder and layout will contain in the res folder.
Now open the res->layout->activity_main.xml file, there you will see two options at the left bottom of the screen, they are Design and Text. With the Design mode, you can drag and drop controls in the UI. Then drag two buttons in the layout and give appropriate text and id to both of the buttons.
Now go to the MainActivity.java file and load the XML file to java using setContentView in the onCreate() method. Now load your XML resources into java variable using the following code.
- Button showDialogueButton = (Button) findViewById(R.id.showDialogueButton);
- Button showToastButton = (Button) findViewById(R.id.showToastButton);
The id should be the same that you use in the layout file.
Then add click listeners for the two buttons. For showing dialogue we need to use AlertDialogue.Builder class in Android. There are some methods to set the message that we need to show to the user and options for adding Positive and Negative buttons, like the following,
Step 3
- AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
- builder.setMessage("This is a dialogue");
- builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
- {
- @Override public void onClick(DialogInterface dialogInterface, int i) {}
- });
- builder.setNegativeButton("No", new DialogInterface.OnClickListener()
- {
- @Override public void onClick(DialogInterface dialogInterface, int i) {}
- });
- builder.show();
Don't forget to call builder.show(); this method is used for showing the dialogue to the user.
Now add click listener for show toast button click like the following,
- showToastButton.setOnClickListener(new View.OnClickListener()
- {
- @Override public void onClick(View view)
- {
- Toast.makeText(MainActivity.this, "This is a Toast", Toast.LENGTH_SHORT).show();
- }
- });
For this, we can use Toast class, and it has a static method named makeText which will accept three parameters context, message, and duration of the toast to show in front of the user.
Please see the output also,