- activity_main.xml
- MainActivity.java
- 2 Toasts
- 2 Buttons
-> We will display a long timed Toast when we will click on a button and a short timed when clicked on another button.
Step 1 : Make an android application Project with any name say ToastDemo.
Step 2 : Drag a button in activity_main.xml layout found in res->layout from the Palette.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="69dp" android:layout_marginTop="68dp" android:text="Long timed toast" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:layout_marginTop="40dp" android:text="Short timed toast" /> </RelativeLayout>
Step 3 : Select MainActivity.java from src folder. Write the below code in the file.
MainActivity.java
package com.mia.toastdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
Button b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "long timed message", Toast.LENGTH_LONG).show();
}
});
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "short timed message", Toast.LENGTH_SHORT).show();
}
});
}
}
Step 4 : Run the Project (Click on a Button and Toast will appear).
Stay Tuned with Made In Android












No comments:
Post a Comment