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

DK
April 1, 2020, 8:03 a.m.
Dmitry Kozhinov

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

  • Result:40points,
  • Rating points-8
A
March 30, 2020, 12:47 p.m.
Anna

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

  • Result:60points,
  • Rating points-1
A
March 29, 2020, 12:14 p.m.
Alexanderv66

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

  • Result:71points,
  • Rating points1
Last comments
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
March 27, 2020, 2:47 a.m.
Andrej Jankovich

Ошибка с ярлыками в Windows исправлена в версиии 1.4.0.4
March 26, 2020, 1:37 p.m.
Andrej Jankovich

но появятся ярлыки, сейчас поправим
Now discuss on the forum
April 2, 2020, 4:53 a.m.
Evgenij Legotskoj

хотя, если вниметльно посмотреть на метод lineNode, то скорее всего проблема в том, что ты создаешь материал в начале метода. Старый скорее всего не удаляется, пока не была удалена нода, а прост…
April 2, 2020, 2:48 a.m.
Evgenij Legotskoj

да нет, правильно код там написан. Может быть дело в том, что чего-то не хватает из dev библиотек, gstreamer тот же самый.
April 2, 2020, 2:46 a.m.
Evgenij Legotskoj

Я думаю, что это где-то описано, но в такой глубине документации и максимум в самых базовых вещах, то есть отдельно в классах этого не пишут, просто потому, что придётся писать для каждого класс…
I
April 1, 2020, 5:57 p.m.
Il'ja

спасибо за ответ! Попробую больше тестов, поищу зависимости. Если проблема решится, то отпишусь здесь :)
April 1, 2020, 4:37 p.m.
Docent

За это отвечает QSvgRender, перед тем как кинуть картинку на виджет её через QSvgRender в QPixMap прогнать надо. Делается это в методе ::render(&) "The QSvgRenderer class is used t…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB