Urichalex
@Urichalex
Кратко о себе)

Как в Android сделать splashscreen?

Есть сайт для мобильных устройств. Делаю под него приложение android webview
При открытии приложения на несколько секунд появляется белый экран, потом только открывается сам сайт.
С андроидостроением столкнулся впервые. Стало интересно, решил сделать сам.
Гуглил в интернетах и вроде даже нагуглил что-то нужное. Открывает мой splashscreen но, перед где-то секунду открытием заставки и где-то пол-секунды после того, как заставка закорется, все равно есть белый экран.
Я уже пытался закрасить экран цветом, но не прокатило.
В res/drawable лежит сама заставка splash.jpg и файл стиля для фона splash_bg.xml
Вот мой код:
splash_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient android:angle="90" android:endColor="#292d20"  android:startColor="#292d20" android:type="linear" />
        </shape>
    </item>
</selector>

activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/splash_bg"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/splach_screen"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/splash_bg"
        android:visibility="visible">

        <ImageView
            android:id="@+id/splashScreen"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:autoSizeTextType="uniform"
            android:background="@drawable/splash" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/main_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/splash_bg"
        android:orientation="vertical"
        android:visibility="invisible">
        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipe"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/splash_bg"
                android:visibility="visible" />
        </android.support.v4.widget.SwipeRefreshLayout>
    </LinearLayout>
</LinearLayout>

MainActivity.java
package com.example.urichalex;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    private Activity activity;
    private SwipeRefreshLayout swipe;

    public MainActivity()
    {
        activity = this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView);
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(activity)
                        .setTitle("Confirm action")
                        .setMessage(message)
                        .setPositiveButton(
                                android.R.string.ok,
                                new DialogInterface.OnClickListener()
                                {
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        result.confirm();
                                    }
                                }
                        )
                        .setNegativeButton(
                                android.R.string.cancel,
                                new DialogInterface.OnClickListener()
                                {
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        result.cancel();
                                    }
                                }
                        )
                        .create()
                        .show();
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                swipe.setRefreshing(false);
                MainActivity.this.setTitle(view.getTitle());
                if (findViewById(R.id.splach_screen).getVisibility() == View.VISIBLE) {
                    // show webview
                    findViewById(R.id.main_view).setVisibility(View.VISIBLE);
                    // hide splash screen
                    findViewById(R.id.splach_screen).setVisibility(View.GONE);
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                // будут открываться внутри приложения
                if (url.contains("example.com")) {
                    return false;
                }
                // все остальные ссылки будут спрашивать какой браузер открывать
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                activity.startActivity(intent);
                return true;
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");
            }
        });
        webView.loadUrl("http://example.com/");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
  • Вопрос задан
  • 795 просмотров
Решения вопроса 1
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы