如何在 webview 中创建后退按钮? [英] How can I create a back button in a webview?

查看:29
本文介绍了如何在 webview 中创建后退按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该应用程序包含两个活动:第一个 - 一个列表视图,其中包含来自资产的 HTML 文件的链接,第二个 - 一个包含此 HTML 文件的网络视图.

The app consists of two activities: first - a listview with links to HTML files from assets, second - a webview with this HTML file.

所以这个 HTML 文件中有一些链接(在下文中我称它为第一个 HTML 文件),这些链接从资产中通向其他 HTML 文件.在我跟随其中一个链接之后,我想回到第一个 HTML 文件.但是这个方法显示的是一个白屏而不是文件的内容.

So there are some links in this HTML file (in the following I call it the first HTML file) leading to other HTML files from assets. After I followed one of this links I want to go back to the first HTML file. But this method shows me a white screen instead of the file's content.

PS:我通过 HTML 链接引用了第一个资产文件中的第二个资产文件.例如(第一个 HTML 文件中的链接代码):

PS: I reference the second asset file from first one by an HTML link. For example (code of link in the first HTML file):

<a href="file:///android_asset/second.html">Second file</a>

这是 WebViewActivity 代码:

public class WebViewActivity extends Activity implements OnClickListener {
    WebView wWebView;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (wWebView.canGoBack() == true) {
                    wWebView.goBack();
                } else {
                    finish();
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bundle bundle = getIntent().getExtras();

        String htmlFileName = "m" + bundle.getString("defStrID") + ".html";
        Context context = getBaseContext();

        try {
            String text = readAssetTextFile(context, htmlFileName);

            wWebView = (WebView) findViewById(R.id.webview);
            String summary = "<html><body>" + text + "</body></html>";
            wWebView.getSettings().setJavaScriptEnabled(true);
            wWebView.loadDataWithBaseURL("x-data://base", summary, "text/html",
                    "utf-8", null);
        } catch (IOException e) {
            Log.e("TAG", "Exception thrown", e);
        }
    }

    public static String readAssetTextFile(Context ctx, String fileName)
            throws IOException
    {
        InputStream inputStream = ctx.getAssets().open(fileName);

        InputStreamReader inputreader = new InputStreamReader(inputStream);
        BufferedReader buffreader = new BufferedReader(inputreader);
        String line;
        StringBuilder text = new StringBuilder();

        try {
            while ((line = buffreader.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        } catch (IOException e) {
            Log.e("TAG", "Exception thrown", e);
        }
        return text.toString();
    }
}

推荐答案

您的问题是 wWebView 类成员变量未初始化,因此为空.查看代码的这一部分:

Your problem is that the wWebView class member variable is not initialized so it is null. See this part of your code:

WebView wWebView = (WebView) findViewById(R.id.webview);

完美,您正在初始化,但不是您认为的那样:您为该方法声明一个局部变量并对其进行初始化.但是,由于具有相同名称的局部变量,您隐藏了类成员 wWebView.因此,您不会初始化类成员,它为 null 并且您会得到 NPE.将上面的行更改为(注意没有类型):

Perfect, you are initializing, but not what you think you are: you declare a local variable for the method and initialize it. However you shadow the class member wWebView, because of the local variable with the same name. Thus you do not initialize the class member, it is null and you get your NPE. Change the above line to (note the absence of the type):

wWebView = (WebView) findViewById(R.id.webview);

EDIT 我一直无法让您在页面之间导航的方式起作用.但是,我对您的 onCreate 方法做了某些更改,现在我的设备上一切正常:

EDIT I was never able to make your way of navigating between the pages work. However I did certain changes to your onCreate method and now everything seems fine on my device:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    TextView title = (TextView) findViewById(R.id.app_name);
    title.setText(getString(R.string.app_name));

    Button backButton = (Button) findViewById(R.id.button_back);
    backButton.setOnClickListener(this);

    Button infoButton = (Button) findViewById(R.id.button_info);
    infoButton.setOnClickListener(this);

    Bundle bundle = getIntent().getExtras();

    String htmlFileName = "m" + bundle.getString("defStrID") + ".html";
    String LINK_TO_ASSETS = "file:///android_asset/";
    wWebView = (WebView) findViewById(R.id.webview);
    wWebView.getSettings().setJavaScriptEnabled(true);
    wWebView.loadURL(LINK_TO_ASSETS + htmlFileName);
}

现在您还需要更改加载的 HTML 文件的内容.首先在资产中每个文件的开头添加 并在末尾添加 .其次,您现在需要更改链接.例如,您在问题中包含的链接:

Now you need to change also the contents of the HTML files you load. First of all add the <html><body> at the beginning of each file in the assets and </body></html> at the end. Second now you will need to change your links. For example the link you have included in your question:

<a href="second.html">Second file</a>

如您所见,这些现在变成了相对链接.所有这些更改可能会使您的 readAssetTextFile 无用,但我相信这是更易于理解的代码.

As you see, these become now relative links. All these changes might make your readAssetTextFile useless, but I believe this is easier-to-understand code.

这篇关于如何在 webview 中创建后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆