当我按下后退按钮时,退出弹出窗口和之前的网页

时间:2017-04-04 15:55:57

标签: android webview main-activity

当我按下后退按钮然后退出弹出窗口和上一页(在webview中)一起出现。它应首先进入上一页,在它应该要求退出的最后一页上。 Plzzzzzzzz帮助

MainActivity.java

package com.ravi.demoapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

import android.app.Activity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity{

    private Fragment contentFragment;
    String testDevice = "D0A04359EA1ECE9BA0CD4B6F457A9991";
    String testDevice2 = "63C3530DA03C191310DB9AB8F0672E5C";
    String testDevice3 = "801F2141A1DC3F743363AFDFDC42AF3A";
    private InterstitialAd mInterstitialAd;
    private AdView mAdView;
    boolean displayAd = false;
    WebView mainWebView;

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

        mainWebView = (WebView) findViewById(R.id.mainWebView);
        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mainWebView.loadUrl(this.getString(R.string.channel_url));

        mAdView = (AdView) findViewById(R.id.ad_view);
        // Create an ad request. Check your logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(testDevice)
                .addTestDevice(testDevice2)
                .addTestDevice(testDevice3)
                .build();

        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                displayAd = true;
//              View servername = findViewById(R.id.txt_List);
//              RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) servername.getLayoutParams();
//              layoutparams.addRule(RelativeLayout.BELOW, mAdView.getId());
//              layoutparams.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
//              servername.setLayoutParams(layoutparams);
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                if (!displayAd) {
                }
            }

            @Override
            public void onAdClosed() {
                // Proceed to the next level.
            }
        });

        // Start loading the ad in the background.
        mAdView.loadAd(adRequest);


        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        // Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

    private class MyCustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private InterstitialAd newInterstitialAd() {
        InterstitialAd interstitialAd = new InterstitialAd(this);
        interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
            }

            @Override
            public void onAdClosed() {
                // Proceed to the next level.
                finish();
                //goToNextLevel();
            }
        });
        return interstitialAd;
    }

    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and reload the ad.
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();

        } else {
            finish();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//      getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private void loadInterstitial() {
        // Disable the next level button and load the ad.
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(testDevice)
                .addTestDevice(testDevice2)
                .addTestDevice(testDevice3)
                .setRequestAgent("android_studio:ad_template").build();
        mInterstitialAd.loadAd(adRequest);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if (event.getAction() == KeyEvent.ACTION_DOWN){switch(keyCode){case 
KeyEvent.KEYCODE_BACK:
            if (mainWebView.canGoBack()) {
                mainWebView.goBack();
            }else{
            finish(); return true;}}
    }
        // If it wasn't the Back key or there's no web page history, bubble 
up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }


    /*
     * We call super.onBackPressed(); when the stack entry count is > 0. if it
     * is instanceof EmpListFragment or if the stack entry count is == 0, then
     * we prompt the user whether to quit the app or not by displaying dialog.
     * In other words, from EmpListFragment on back press it quits the app.
     */
    @Override
    public void onBackPressed() {
        onShowQuitDialog();
    }

    public void onShowQuitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);

        builder.setMessage("Do You Want To Quit?");
        builder.setPositiveButton(android.R.string.yes,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        showInterstitial();
                    }
                });
        builder.setNegativeButton(android.R.string.no,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder.create().show();
    }

}

Actvity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <com.google.android.gms.ads.AdView
        android:id="@+id/ad_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        ads:adUnitId="@string/banner_ad_server_list_unit_id"
        ads:adSize="BANNER"/>

    <WebView android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/ad_view"
        android:id="@+id/mainWebView">
    </WebView>


</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

你有更多活动吗?试试这个:



[CustomEditor(typeof(Parser))] public class ParserEditor : Editor{

public override void OnInspectorGUI()
{
    Parser myTarget = (Parser)target;

    DrawDefaultInspector();

    if (GUILayout.Button("Do Thing"))
    {
        // I want thnis to happen when Do Thing button is pressed
        Debug.Log("Do the thing: " + myTarget.path);
    }
}

答案 1 :(得分:0)

使用Stack实现:如果您想通过按返回按钮转到上一个网页,则必须执行两项操作。

  1. 覆盖window.myValues = {}; function fetchValue(){ var bill = JSON.parse(localStorage.getItem('bill')); var result = document.getElementById('total'); result.innerHTML=''; var total=0; for(var i=0;i < bill.length;i++){ var items= bill[i].items; var date= bill[i].date; var price= bill[i].price; total+= parseFloat(price); } return total; } window.myValues.total = fetchValue(); // window.myValues.total is available everywhere with if(window.myValues) { // .... window.myValues.total }
  2. onBackPressed保存您之前的网页地址。
  3. 声明Stack类型String

    stack

    当加载新网址时,将当前网址放入堆叠。像

    private Stack<String> stack = new Stack<>();
    

    现在,覆盖 private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { stack.add(url); } }

    onBackPressed

    此处,@Override public void onBackPressed() { if (stack.size() > 1 && stack != null) { stack.pop(); load(stack.peek()); } else { super.onBackPressed(); } } } 是加载网页的方法。

    load()

    使用WebView Native API:(如您所述)

      private void load(String urlToLoad) {
    
        pd = new ProgressDialog(YourActivity.this);
        pd.setMessage("Please wait Loading...");
        pd.show();
    
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webView.loadUrl(urlToLoad);
        webView.setWebViewClient(new MyWebViewClient());
    
    }
    

    无需覆盖@Override public void onBackPressed() { if(mainWebView.canGoBack()) mainWebView.goBack(); else onShowQuitDialog(); }