load textfile in webview android

家住魔仙堡 提交于 2019-12-06 04:28:21

问题


so far i have read how to load "normal" html webpages in a webview .. so far I pass the URL containing the path of my text file but it loads nothing. this is my method:

@Override
public void onSelected(String url) {
    ViewerFragment viewer = (ViewerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.view_fragment);

    if (viewer == null || !viewer.isInLayout()) {
        Intent showContent = new Intent(getApplicationContext(),
                ViewerFragment.class);
        showContent.setData(Uri.parse(url));
        startActivity(showContent);
    } else {
        viewer.updateUrl(url);
    }

}

and the viewer fragment got this:

    public class ViewerFragment extends Fragment{
    private WebView viewer = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        viewer = (WebView) inflater
                .inflate(R.layout.details_fragment, container, false);
        return viewer;
    }

    public void updateUrl(String newUrl) {
        if (viewer != null) {
            viewer.loadUrl(newUrl);
        }
    }
    }

but keep getting this screen:

any ideas how to do this? =/ I already tried googling a bit but didnt find much info about it... actually found almost none. So any help would be appreciated.


回答1:


Try reading the contents of the text file and prefixing the text with <html><body> then append </body></html> then use the WebView method loadData(...).

Example:

StringBuilder sb = new StringBuilder("<html><body>");
sb.append(readTextFile());
sb.append("</body></html>");
myWebView.loadData(sb.ToString(), "text/html", "UTF-8");

public String readTextFile(String filename) {
    // Open and read the contents of <filename> into
    // a single string then return it
}


来源:https://stackoverflow.com/questions/8720201/load-textfile-in-webview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!