load textfile in webview android

2019-04-10 07:40发布

问题:

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
}