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
e
  • ehot
  • March 31, 2024, 2:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks