Evgenii Legotckoi
Evgenii LegotckoiJuly 26, 2015, 10:12 a.m.

Toast - Customization pop-up message on the Android

Give customization of all applications under OS Android !!!

With the slogan I want to tell today about customization pop-up message (Toast) in the Android OS. In any application that is designed and developed with great care, the question may arise about the customization of even such an element as a popup message. After the success of the application depends not only on ideas and utility, but also from the sale of the appearance of the parts, even the smallest and seemingly not very important.

Project structure

This lesson is to write an application that will display a customized pop-up message by pressing a button, which will not be subject of customization.

In the Project there are two classes:

  1. MainActivity
  2. MyListAdapter - which is responsible for the transmission of data in the form of a list item

Also, the project contains the following resource files:

  1. activity_main.xml
  2. toast_info.xml - pop-up message marking
  3. toast_border:xml - additional markup for background of pop-up message
  4. ic_info.png - Image Information icon, which will be used in the pop-up message
  5. string.xml - string constants file

The formation of apps layout

activity_main.xml

Layout main Activiti, where it will be called a pop-up message

<LinearLayout 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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#ffffff"
    android:orientation="vertical">

    <TextView android:text="@string/check_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/push_me"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"/>

</LinearLayout>

toast_info.xml

Markup File pop-up message. This file is determined by the layout of two elements:

  • ImageView - which will put an icon image information;
  • TextView - element that will fit your message.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/toast_border">

        <ImageView
            android:id="@+id/imageView1"
            android:src="@mipmap/ic_info"
            android:padding="4dp"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_gravity="center_vertical"
            android:contentDescription="ToastPicture" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:maxWidth="260dp"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:text="Android Tutorial Custom Toast"
            android:textColor="#fff"
            android:textSize="24sp"
            android:layout_gravity="center_vertical"/>

</LinearLayout>

toast_border.xml

XML-file, which is customizable drawing borders and corner rounding pop-up message.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <padding android:left="8dp" android:top="8dp"
        android:right="8dp" android:bottom="8dp" />

    <corners android:radius="10dp" />

    <solid android:color="#661f1f21"/>
</shape>

The main project class - MainActivity.java

In this class, is launched basic Activiti project, which will be called from the customized Toast .. The project was created in Android Studio just finished with Activiti (Blank Activity Project).

This class implements OnClickListener method and is its redefinition @Override. In this method, there is a call and a pop-up message with a single line.

package ru.evileg.customtoast;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private static Button button;

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

        /*
         * Initialize button, by clicking on which will cause a pop-up message
         */
        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        /*
         * Вызов всплывающего сообщения
         */
        CustomToast.makeText(this, R.string.toast_message).show();
    }
}

CustomToast.java

This class is used to generate customized messages. Toast essence of customization in this class is reduced to inherit an existing class Toast, followed by initializing its own layout pop-up message and icon image information system. Also present in the class of several methods to set the text message. Posts Call inherited done show () method of the parent class Toast, as shown in Listing Class MainActivity.

package ru.evileg.customtoast;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Application FinancialAccounting
 * Created by EvILeg on 26.07.2015.
 */
public class CustomToast extends Toast {

    private static TextView toastText;
    /**
     * Construct an empty Toast object.  You must call {@link #setView} before you
     * can call {@link #show}.
     *
     * @param context The context to use.  Usually your {@link Application}
     *                or {@link Activity} object.
     */
    public CustomToast(Context context) {
        super(context);

        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        /*
         * Produced markup initializing pop-up message, 
         * set the icon image information in a pop-up message
         */
        View rootView = inflater.inflate(R.layout.toast_info, null);
        ImageView toastImage = (ImageView) rootView.findViewById(R.id.imageView1);
        toastImage.setImageResource(R.mipmap.ic_info);
        toastText = (TextView) rootView.findViewById(R.id.textView1);

        /*
         * Set initialized appearance, location pop-up message on the screen,
         * as well as the duration of the message
         */
        this.setView(rootView);
        this.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        this.setDuration(Toast.LENGTH_SHORT);
    }

    /*
     * The method call messages without installing the duration of the existence of the 
     * transfer of the message of the text information as a sequence of text characters or strings
     */
    public static CustomToast makeText(Context context, CharSequence text) {
        CustomToast result = new CustomToast(context);
        toastText.setText(text);

        return result;
    }

    /*
     * The method call message with installing the duration of existence and 
     * with the transmission of the message of the text information 
     * as a sequence of text characters or strings
     */
    public static CustomToast makeText(Context context, CharSequence text, int duration) {
        CustomToast result = new CustomToast(context);
        result.setDuration(duration);
        toastText.setText(text);

        return result;
    }

    /*
     * The method call messages without installing the duration of the existence of 
     * the transfer of the message text resource ID
     */
    public static Toast makeText(Context context, int resId)
            throws Resources.NotFoundException {
        return makeText(context, context.getResources().getText(resId));
    }

    /*
     * The method call message with installing the duration of existence and 
     * with the transmission of the message of the text resource ID
     */
    public static Toast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException {
        return makeText(context, context.getResources().getText(resId), duration);
    }
}

Result

If in the process of studying the material did not have any problems and errors, by pressing a button should appear a pop-up message that resembles the following.

Click the button to see a pop-up message

And here is the pop-up message

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks