Android实现EditText的富文本编辑-创新互联
前言

本文是我之前写的这篇文章《Android图文混排-实现EditText图文混合插入上传》的升级版,除了在EditText实现了图片上传之外,还包含了视频上传、云盘文件上传、录音上传以及显示上传进度。目前应用于蜜蜂-集结号-任务模块。
首先介绍一下该功能的实现效果:
实现思路
实现思路与之前介绍的稍有不同,但是依然是使用SpannableString实现的。由于这里不仅仅支持图片上传,还支持音频、视频、文件上传,为了以后方便扩展更多类型,这里不再使用标签实现,而是直接以JSON实现。以前的实现思路是"",现在每一个富文本元素都是"{"type":"video", "data":{ "url":"xxx.mp4", "thumb":"base64 str", "size":1024 }}" 这样的字符串替换出来的,"type"有"video","audio","image","text","file"等类型,针对不同类型,"data"里面的字段也不同。"data"里面一般包含文件名、文件大小、文件网络路径、音视频长度等字段。
图片或视频的上传进度改变时,切回主线程不断更新UI,所谓更新UI,其实就是不断的去替换这个SpannableString。对于各种样式的ImageSpan,实际上都是BitmapDrawable。
实现富文本元素插入到EditText中
实现代码如下:
public static TaskSpan getAudioSpan(Context context, int type, String json, String time, int progress) {
View spanView = View.inflate(context, R.layout.bbs_audio_bar_tag, null);
LinearLayout llBg = (LinearLayout) spanView.findViewById(R.id.ll_bg);
ImageView icPlay = (ImageView) spanView.findViewById(R.id.iv_play);
ImageView icStop = (ImageView) spanView.findViewById(R.id.iv_stop);
TextView tvTime = (TextView) spanView.findViewById(R.id.tv_time);
ProgressBar proBar = (ProgressBar) spanView.findViewById(R.id.progress_bar);
switch (type) {
case AUDIO_PLAY_NONE:
try {
final String[] split = json.split(BBSConstants.SPLIT_TAG);
JSONObject obj = new JSONObject(split[1]);
final JSONObject data = obj.optJSONObject(Constants.RETURN_DATA);
int duration = data.optInt(BBSConstants.LONG_DATA_DURATION);
tvTime.setText(DateUtil.getDurationTime(duration / 1000, false));
proBar.setProgress(0);
icPlay.setVisibility(View.VISIBLE);
icStop.setVisibility(View.GONE);
llBg.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.grey_bg_50dp_corner_no_border));
} catch (JSONException e) {
e.printStackTrace();
}
break;
case AUDIO_PLAY_ING:
proBar.setProgress(progress);
icPlay.setVisibility(View.GONE);
icStop.setVisibility(View.VISIBLE);
llBg.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.blue_bg_50dp_corner_no_border));
tvTime.setText(time);
break;
}
BitmapDrawable drawable = (BitmapDrawable) ViewUtil.convertViewToDrawable(spanView);
drawable.setTargetDensity(MyApplication.getInstance().getResources().getDisplayMetrics());
final float scale = 1.0f / 6.0f;
final int width = DeviceUtil.getScreenWidth((Activity) context) - DeviceUtil.dip2px(context, LENGTH);
float height = (float) width * scale;
drawable.setBounds(0, 0, width, (int) height);
return new TaskSpan(drawable, type, json);
}
网页题目:Android实现EditText的富文本编辑-创新互联
文章路径:http://www.jxjierui.cn/article/jpije.html


咨询
建站咨询
