0

Делаю обозреватель для сайта с использованием компонента WebView . И все бы хорошо, но мне нужно сделать чтобы если пользователь открывает приложение, то сразу на экране он бы видел экран values/load.xml , и чтоб этот экран стоял покуда страница не загрузится. После нужно чтоб просто открывался сайт в этом приложении.

Пробывал делать АсинТаск, но у меня получилось что экран load.xml появлялся на долю секунды, а после просто белая страница.

Вот код обозревателя с АсинТаск:

public class MainActivity extends Activity {
private static final String PREFS_NAME = null;
protected static String LASTURL = null;
private WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (WebView) findViewById(R.id.wv);
    new checkAuth().execute();



WebSettings webSettings = wv.getSettings();
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
final boolean imgOn = settings.getBoolean("IMGMODE", false);
webSettings.setLoadsImagesAutomatically(imgOn);

final Activity activity = this;

wv.setWebChromeClient(new WebChromeClient() {
  public void onProgressChanged(WebView view, int progress)
  {
    activity.setTitle(" "+LASTURL);
    activity.setProgress(progress * 100);
    if(progress == 100)
      activity.setTitle(" "+LASTURL);
  }
});
wv.setWebViewClient(new WebViewClient() {
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    Toast.makeText(getApplicationContext(), "Error: " + description+ " " + failingUrl, Toast.LENGTH_LONG).show();
  }

  @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    if (url.indexOf("wapey")<=0) {

      Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
      startActivity(intent);
      return true;
    }
    return false;
  }

  public void onPageStarted (WebView view, String url, Bitmap favicon) {
    LASTURL = url;
    view.getSettings().setLoadsImagesAutomatically(true);
  }

  public void onPageFinished (WebView view, String url) {
    view.loadUrl("javascript:(function() { " +
        "hide('sidebar');"+
        "var panel = document.getElementById('search');"+
        "panel.style['width'] = '55px';"+
        "function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}"+              //"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+
        "})()");
    if (imgOn) view.getSettings().setLoadsImagesAutomatically(true);
  }
});

   // wv.loadUrl("http://site.ru");
  }

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



  private void saveSettings(Boolean val)
  {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("IMGMODE", val);
editor.commit();
 }


  private class checkAuth extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        setContentView(R.layout.load);

    }

    @Override
    protected Void doInBackground(Void... params) {
        wv.loadUrl("http://site.ru");
        return null;

    }


    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        setContentView(R.layout.activity_main);

    }


    }

А вот без АсинТаск:

    public class MainActivity extends Activity {
private static final String PREFS_NAME = null;
protected static String LASTURL = null;
private WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (WebView) findViewById(R.id.wv);
    new checkAuth().execute();



WebSettings webSettings = wv.getSettings();
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
final boolean imgOn = settings.getBoolean("IMGMODE", false);
webSettings.setLoadsImagesAutomatically(imgOn);

final Activity activity = this;

wv.setWebChromeClient(new WebChromeClient() {
  public void onProgressChanged(WebView view, int progress)
  {
    activity.setTitle(" "+LASTURL);
    activity.setProgress(progress * 100);
    if(progress == 100)
      activity.setTitle(" "+LASTURL);
  }
});
wv.setWebViewClient(new WebViewClient() {
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    Toast.makeText(getApplicationContext(), "Error: " + description+ " " + failingUrl, Toast.LENGTH_LONG).show();
  }

  @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    if (url.indexOf("wapey")<=0) {

      Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
      startActivity(intent);
      return true;
    }
    return false;
  }

  public void onPageStarted (WebView view, String url, Bitmap favicon) {
    LASTURL = url;
    view.getSettings().setLoadsImagesAutomatically(true);
  }

  public void onPageFinished (WebView view, String url) {
    view.loadUrl("javascript:(function() { " +
        "hide('sidebar');"+
        "var panel = document.getElementById('search');"+
        "panel.style['width'] = '55px';"+
        "function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}"+              //"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+
        "})()");
    if (imgOn) view.getSettings().setLoadsImagesAutomatically(true);
  }
});

   wv.loadUrl("http://site.ru");
  }

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



  private void saveSettings(Boolean val)
  {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("IMGMODE", val);
editor.commit();
 }




    }

То есть другими словами надо поставить экран заглушку, покуда грузится страница.

0

1 ответ 1

2

Для реализации того, что Вам нужно, необходимо оформить каркас main_activity.xml в следующем виде:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ... >
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ... />
    <include layout="@layout/load.xml"/>
</RelativeLayout>  

Допустим, ваша заглушка load.xml имеет такой каркас:

<RelativeLayout
    android:id="@+id/onLoadingView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ... >
    содержимое заглушки
</RelativeLayout>

Теперь в вашей активности MainActivity нужно найти по id вашу заглушку. Для этого после private WebView wv; добавьте строку RelativeLayout onLoadingView;

Теперь в методе onCreate после

wv = (WebView) findViewById(R.id.wv);

добавьте строку

onLoadingView = findViewById(R.id.onLoadingView);

Предпоследний шаг. Когда WebView wv начинает загрузку страницы, срабатывает метод onPageStarted, в него можно добавить (на ваше усмотрение) строку (если хотите при последующих загрузках страниц показывать вашу заглушку)

onLoadingView.setVisibility(View.VISIBLE);

И последним шагом станет добавление в метод onPageFinished следующей строки

onLoadingView.setVisibility(View.GONE);

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.