android+写入html,android - 向textview中写入HTML代码(完美解决下滑问题,和线程不能操作主线程问题)...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值