SplashScreen в Android, называется заставка перед запуском основного приложения, она позволяет устанавливать изображения, логотипы, короткие видео ролики, текст поясняющего или предупреждающего содержания.
Содержание:
- Новый проект
- Создаем слой
- Настройка манифеста
- Код заставки SplashScreen
- Тест в эмуляторе Android
- Изменение времени отображения заставки
- Полный текст AndroidManifest.xml
- Полный текст strings.xml
- Полный текст activity_main.xml
- Полный текст splashscreen.xml
- Полный текст MainActivity.java
- Полный текст SplashScreen.java
- В этом видео пишем заставку SplashScreen в Android:
Новый проект
В android studio давайте создадим новый проект, назовём его My Splash Screen. В папку Drawable добавим изображения (2 штуки), с локального диска. Я их заранее подготовил, скопируем, нажмем правой кнопкой на эту папку drawable и вставим. Как видите они появились android и logo.
Создаем слой
Добавим новый слой для нашего splashscreen, назовём его точно так же splashscreen. Создадим новый класс java SplashScreen. Этот класс будет наследоваться от класса Activity.
Изменим тип слоя LinearLayout в splashscreen.xml на RelativeLayout. Из компонентов Images добавим в разметку элемент ImageView. В свойствах укажем рисунок android, нажмем Ok.Изменим расположение wrap_content на match_parent. Изменим рисунок на logo, тип масштабирование установим matrix. Добавим еще один ImageView и зададим ему изображение android. Скопируем ранее внесенные свойства расположения на match_parent. Сохраним наш проект.
<imageview
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaletype="matrix"
android:src="@drawable/logo"
android:contentdescription=""
tools:ignore="ContentDescription"></imageview>
<imageview
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaletype="fitCenter"
android:src="@drawable/android"
android:contentdescription=""
tools:ignore="ContentDescription"></imageview>
Настройка манифеста
В файле AndroidManifest.xml нам нужно будет описать наш splashscreen activity, я скопирую описание MainActivity и изменю название на SplashScreen. Для MainActivity в свойстве категории name заменю LAUNCHER на DEFAULT.
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter></activity>
Изменим надпись Hello World! на другой текст, для этого в файле strings.xml добавим еще один строковый ресурс с именем name и в его свойства напишем название нашей программы - "КОМПЬЮТЕПАПИЯ".
<string name="name">КОМПЬЮТЕРАПИЯ</string>
В свойствах TextView изменим значение text на @string/name.
<textview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
app:layout_constraintbottom_tobottomof="parent"
app:layout_constraintleft_toleftof="parent"
app:layout_constraintright_torightof="parent"
app:layout_constrainttop_totopof="parent"></textview>
Код заставки SplashScreen
В файл SplashScreen.java добавим функцию onCreate, скопировав ее из MainActivity, изменим название слоя activity_main на splashscreen. Введем переменную типа int SPLASH_DISPLEY_LENGHT со значением 5000, это означает, что наш splashscreen будет отображаться 5 секунд, после этого произойдет переход на MainActivity.
private final int SPLASH_DISPLAY_LENGHT = 5000;
В onCreate напишем новую функцию Handler через метод postDelayed, через вызов функции run вызовем MainActivity, через время указанное в SPLASH_DISPLEY_LENGHT.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent mainIntent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(mainIntent);
SplashScreen.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
Так же добавим функцию onBackPressed, это обработка нажатия на кнопку назад на телефоне.
@Override
public void onBackPressed() {
super.onBackPressed();
}
Тест в эмуляторе Android
Запустим эмулятор Android, что бы посмотреть, как работает наше приложение, как видим -splashscreen слой отображался 5 секунд, на нем не было изображений, и произошел переход в MainActivity.
Разберемся, почему так происходит. Проблема содержится в файле splashscreen.xml в строках
app:scrCompat="@drawable/logo"
app:scrCompat="@drawable/android"
Изменим их на эти:
android:scr="@drawable/logo"
android:scr="@drawable/android"
Изменение времени отображения заставки
Предложенное по умолчанию значение, по каким-то причинам не отображает в приложении наши изображения. Перезапустим наше приложение в эмуляторе Android, и увидим, что все прекрасно работает, по истечении 5 секунд происходит переход на главную активность приложения.
Изменим значение переменной SPLASH_DISPLEY_LENGHT с 5000 на 2000 и увидим при запуске, что интервал видимости splashscreen уменьшился до 2 секунд. Практически очень быстро появляется. Вернем значение 5000 обратно, и все работает, как и раньше.
Возможно различное масштабирование элемента imageView, я сделаю один слой невидимым через свойство visibili. Доступны типы: matrix, fitXY, fitStart, fitCenter, fitEnd, center, centerCrop, centerInside для отображения рисунков на экране.

Полный текст AndroidManifest.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.maxfad.mysplashscreen">
<application
android:allowbackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundicon="@mipmap/ic_launcher_round"
android:supportsrtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
</application>
</manifest>
Полный текст strings.xml
<resources>
<string name="app_name">My SplashScreen</string>
<string name="name">КОМПЬЮТЕРАПИЯ</string>
</resources>
Полный текст activity_main.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<android.support.constraint.constraintlayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ru.maxfad.mysplashscreen.MainActivity">
<textview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
app:layout_constraintbottom_tobottomof="parent"
app:layout_constraintleft_toleftof="parent"
app:layout_constraintright_torightof="parent"
app:layout_constrainttop_totopof="parent"></textview>
</android.support.constraint.constraintlayout>
Полный текст splashscreen.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<relativelayout
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:src="@drawable/logo">
<imageview
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaletype="matrix"
android:src="@drawable/logo"
android:contentdescription=""
tools:ignore="ContentDescription"></imageview>
<imageview
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaletype="fitCenter"
android:src="@drawable/android"
android:contentdescription=""
tools:ignore="ContentDescription"></imageview>
</relativelayout>
Полный текст MainActivity.java
package ru.maxfad.mysplashscreen;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Полный текст SplashScreen.java
package ru.maxfad.mysplashscreen;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
/**
* Created by maxfad on 19.06.2017.
*/
public class SplashScreen extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent mainIntent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(mainIntent);
SplashScreen.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
SplashScreen в Android пишем заставку
Рекомендуем смотреть видео в полноэкранном режиме, в настойках качества выбирайте 1080 HD, не забывайте подписываться на канал в YouTube, там Вы найдете много интересного видео, которое выходит достаточно часто. Приятного просмотра!
С уважением, авторы сайта Компьютерапия
Понравилось? Поделись этим видео с друзьями!
SplashScreen в Android пишем заставку
Рекомендуем смотреть видео в полноэкранном режиме, в настойках качества выбирайте 1080 HD, не забывайте подписываться на видео ВКонтакте, там Вы найдете много интересного, которое выходит достаточно часто. Приятного просмотра!
С уважением, авторы сайта Компьютерапия
Понравилось? Поделись этим видео с друзьями!
SplashScreen в Android пишем заставку
Рекомендуем смотреть видео в полноэкранном режиме, в настойках качества выбирайте 1080 HD, не забывайте подписываться на канал в Рутубе, там Вы найдете много интересного, которое выходит достаточно часто. Приятного просмотра!
С уважением, авторы сайта Компьютерапия
Понравилось? Поделись этим видео с друзьями!
<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.maxfad.mysplashscreen">
<application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/AppTheme">
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
</application>
</manifest>


