如何在网页视图创建后退按钮? [英] How to create back button in webview?

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

问题描述

应用程序包括两个活动:第一 - 列表视图链接到从资产的HTML文件,第二个 - 网页视图这个HTML文件。因此,有这个HTML文件的一些链接(下一页我把它称为第一个HTML文件)导致其他HTML文件从资产。之后,我跟着这个链接我要回到第一个HTML之一。但这种方法表明我的白色屏幕,而不是文件的内容。

PS:我用的HTML链接引用从第一个第二个资源文件。例如(在第一个HTML链接的code):

 < A HREF =文件:///android_asset/second.html>第二个文件< / A>

下面就是 WebViewActivity code:

 公共类WebViewActivity扩展活动实现OnClickListener {
    的WebView wWebView;    @覆盖
    公共布尔的onkeydown(INT键code,KeyEvent的事件){
        如果(event.getAction()== KeyEvent.ACTION_DOWN){
            开关(键code){
            案例KeyEvent.KEY code_BACK:
                如果(wWebView.canGoBack()==真){
                    wWebView.goBack();
                }其他{
                    完();
                }
                返回true;
            }        }
        返回super.onKeyDown(键code,事件);
    }
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);        束束= getIntent()getExtras()。        串htmlFileName =M+ bundle.getString(defStrID)+的.html;
        上下文的背景下= getBaseContext();        尝试{
            字符串文本= readAssetTextFile(背景下,htmlFileName);            wWebView =(的WebView)findViewById(R.id.webview);
            字符串摘要=< HTML和GT;<身体GT; +文字+< /身体GT;< / HTML>中;
            wWebView.getSettings()setJavaScriptEnabled(真)。
            wWebView.loadDataWithBaseURL(X-数据://基地,总之,text / html的
                    UTF-8,NULL);
        }赶上(IOException异常五){
            Log.e(TAG,抛出异常,E);
        }
    }    公共静态字符串readAssetTextFile(上下文CTX,字符串文件名)
            抛出IOException异常
    {
        为InputStream的InputStream = ctx.getAssets()打开(文件名)。        InputStreamReader的inputreader =新的InputStreamReader(InputStream的);
        的BufferedReader buffreader =新的BufferedReader(inputreader);
        串线;
        StringBuilder的文本=新的StringBuilder();        尝试{
            而((行= buffreader.readLine())!= NULL){
                text.append(线);
                text.append('\\ n');
            }
        }赶上(IOException异常五){
            Log.e(TAG,抛出异常,E);
        }
        返回text.toString();
    }
}


解决方案

您的问题是, wWebView 类的成员变量未初始化,因此为空。看到你的code的这一部分:

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

完美,要初始化,但是不知道你以为你是:你声明一个局部变量的方法,并对其进行初始化。然而,你的影子,因为具有相同名称的局部变量的类成员 wWebView 。因此,你不要初始化类的成员,它为空,你会得到你的NPE。改变上述行(注意缺少的类型):

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

修改我从来没有能够让你的网页的工作之间进行导航的方式。但是我没有一定的改变你的的onCreate 方法,现在一切似乎我的设备上罚款:

  @覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    的setContentView(R.layout.main);
    TextView的标题=(的TextView)findViewById(R.id.app_name);
    title.setText(的getString(R.string.app_name));    键返回按钮=(按钮)findViewById(R.id.button_back);
    backButton.setOnClickListener(本);    按钮infoButton =(按钮)findViewById(R.id.button_info);
    infoButton.setOnClickListener(本);    束束= getIntent()getExtras()。    串htmlFileName =M+ bundle.getString(defStrID)+的.html;
    字符串LINK_TO_ASSETS =文件:/// android_asset /;
    wWebView =(的WebView)findViewById(R.id.webview);
    wWebView.getSettings()setJavaScriptEnabled(真)。
    wWebView.loadURL(LINK_TO_ASSETS + htmlFileName);
}

现在,你也需要改变你加载HTMLS的内容。首先,添加< HTML><身体GT; 在资产的每个文件的开头和< /身体GT;< / HTML> 结尾。其次,现在你需要改变你的链接。例如,链接已包含在你的问题:

 < A HREF =second.html>第二个文件< / A>

正如你看到这些现在已经成为相对链接。所有这些变化可能会使你的 readAssetTextFile 没用,但我相信这是比较容易理解code。

App consists of two activities: first - listview with links to html files from assets, second - webview with this html file. So there are some links in this html file (Next I call it 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. But this method shows me white screen instead of file's content.

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

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

Here is WebViewActivity code:

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();
    }
}

解决方案

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);

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 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);
}

Now you need to change also the contents of the htmls 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>

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.

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

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