我一直试图让TextView工作以从网址显示我的HTML,但我见过的所有例子都使用字符串,例如
String htmltext = "<h2>Title</h2><br><p>Description here</p>";
myTextView.setText(Html.fromHtml(htmltext));
但我想从我运行的网页上显示。如果我将 htmltext 更改为“www.example.com ,但不会显示内容。
我相信很多人会说使用webview。我看起来就像一个浏览器。
答案 0 :(得分:0)
首先通过提供URL
到getResponseFromUrl(String str)
方法从网页获取所有内容,如下所示。然后,您就可以在TextView
中显示它。
String htmltext = getResponseFromUrl("www.example.com");
myTextView.setText(htmltext);
public static String getResponseFromUrl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream iStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream, "iso-8859-1"), 8);
StringBuilder strBuilder = new StringBuilder();
String line= null;
while ((line= reader.readLine()) != null)
strBuilder .append(line);
String content = strBuilder .toString();
iStream.close();
return content;
}
答案 1 :(得分:0)
最后我用JSoup来完成我的任务。稍后会发布代码
new Thread(new Runnable() {
@Override
public void run() {
try {
//get the Document object from the site. Enter the link of site you want to fetch
Document document = Jsoup.connect("http://www.mywebsite.com.au/message.html").get(); // this is the website string
//Get the text we want
title = document.select("h2").text().toString();
//set the title of text view
//Run this on ui thread because another thread cannot touch the views of main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
//set both the text views
titleText.setText(title);
titleText.setMovementMethod(new ScrollingMovementMethod());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}