You are able to create custom toast in android. So, you can display some images like congratulations or loss on the toast. It means you are able to customize the toast now.
activity_main.xml
Drag the component that you want to display on the main activity.
File: activity_main.xml
- <RelativeLayout xmlns:androclass="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" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/hello_world" />
-
- </RelativeLayout>
customtoast.xml
Create another xml file inside the layout directory. Here we are having ImageView and TextView in this xml file.
File: customtoast.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
- android:id="@+id/custom_toast_layout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:background="#F14E23"
- >
-
- <ImageView
- android:id="@+id/custom_toast_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:contentDescription="@string/hello_world"
- android:src="@drawable/ic_launcher"/>
-
- <TextView
- android:id="@+id/custom_toast_message"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:contentDescription="@string/Toast"
- android:text="@string/Toast" />
- </LinearLayout>
Activity class
Now write the code to display the custom toast.
File: MainActivity.java
- package com.example.customtoast2;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Gravity;
- import android.view.LayoutInflater;
- import android.view.Menu;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
-
- LayoutInflater li = getLayoutInflater();
-
- View layout = li.inflate(R.layout.customtoast,
- (ViewGroup) findViewById(R.id.custom_toast_layout));
-
-
- Toast toast = new Toast(getApplicationContext());
- toast.setDuration(Toast.LENGTH_SHORT);
- toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
- toast.setView(layout);
- toast.show();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
-
- }
No comments:
Post a Comment