Toast - Customization pop-up message on the Android

Android, Toast

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.
Support the author Donate

Comments

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

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

DN
Jan. 28, 2020, 8:01 a.m.
Denis Nikolaev

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

  • Result:14points,
  • Rating points-10
SF
Jan. 27, 2020, 4:10 p.m.
Sergei Filin

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

  • Result:73points,
  • Rating points1
BM
Jan. 26, 2020, 12:16 a.m.
Bekzod Muminov

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

  • Result:53points,
  • Rating points-4
Last comments
m
Jan. 27, 2020, 8:53 p.m.
michaeldevp

Единственная проблема состоит в том, что для выделения QCheckBox приходится дважны нажимать мышь. Получается что сначала выделяется ячейка. а только потом фокус уже попадает на виджет. …
Jan. 27, 2020, 12:01 p.m.
Ruslan Polupan

Да так, посмотрел библиотеку попробовал примеры...
s
Jan. 27, 2020, 1:51 a.m.
shame

Чего не webassembly?
Jan. 22, 2020, 1:12 a.m.
Docent

Полезная статья. Как всегда - то что надо. Добавлю ещё маленькую полезность - после установки tracer (88 строка) и перед выводом значений в lineEdit (91 строка) стоит добавить updatePositio…
Jan. 17, 2020, 1:31 p.m.
Andrej Jankovich

Выглядит как ошибка библиотеки. Расскажите подробно на какой платформе вы собираете проект (MinGW или MSVC) их версии и версии Qt.
Now discuss on the forum
f
Jan. 29, 2020, 11:27 a.m.
fen3der

Добрый день Сломал уже всю голову, никак не могу разобраться с печатью Проблема в следующем: если программа открыта не на весь экран, то документ распечатанный выглядит так …
s
Jan. 29, 2020, 11 a.m.
shuric

Доброго времени суток. Пытаюсь разобраться с QMdiArea. При создании subWindow все понятно, но не могу понять почему при закрытии subWindow не освобождается память. Вот простой при…
Jan. 28, 2020, 1:56 p.m.
Pavel.K

разобрался
Jan. 27, 2020, 2:17 p.m.
Il'ja Chichak

а почему бы не сделать одну модель, например Attachement со всеми этими полями, и в зависимости от действия пользователя, например, "добавить документ", "добавить картинку" и т.д. класть все это…
E
Jan. 26, 2020, 10:42 p.m.
Edi

Другого способа, как получать перезагруженный контент через JavaScript на странице, я не знаю. Получилось сделать без QWebEngineView, с помощью QWebEnginePage, runJavaScrip…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB