android - 向textview中写入HTML代码(完美解决下滑问题,和线程不能操作主线程问题)
2017-08-20 10:38
访问量: 1346
分类:
技术
1. 在View中,记得是外面要嵌套一个 ScrollView, 然后里面是TextView. 例如:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:layout_weight="1.01"
android:fillViewport="true"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
>
android:id="@+id/generic_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/textColor"
/>
2. 在java代码中,先发起一个http请求(必须是异步),然后,在回调success函数中,使用ui.post()函数,让线程回归主线程.
public void setWebViewContent(String url){
Log.d(TAG, "== url to open: " + url);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
/**
* 第一次,开启一个新的线程
*/
okHttpClient.newCall(request).enqueue(new Callback(){
@Override
public void onFailure(Call call, IOException e){
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response){
try{
String content = response.body().string();
Log.d(TAG, "== url got: " + content.length());
JSONObject jObject = new JSONObject(content);
final String htmlContent = jObject.getString("content");
/**
* 第二次,让操作回归主线程
*/
webView.post(new Runnable() {
@Override
public void run() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
webView.setText(Html.fromHtml(htmlContent,Html.FROM_HTML_MODE_LEGACY));
} else {
webView.setText(Html.fromHtml(htmlContent));
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
}
听紫文说,目前不直接用okhttp, 反而是使用框架,例如: retrofit https://github.com/square/retrofit