【发布时间】:2017-07-27 06:01:15
【问题描述】:
我有一个 html 代码,放入一个我想解析的字符串,然后将其转换为不同的视图并在 Android 中按顺序显示每个视图..
HTML 示例:
String htmlText = "
<div class = "quote">
<br>
<br>
Hello how are you today.
<p>
I am fine thank you.
<br>
<br>
<img src="http://testing.jpg"/>
<br>
<br>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
<br>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
<br>
<img src="http://testing2.jpg"/>
</div>";
对于这种情况,我想在 android 中显示各自的 imageviews 和 textviews。但所有这些都必须按升序排列。这很重要,因为内容每次都是动态的,图像可以出现在文本之前/之后等等。
我能够将内容转换为各自的视图,例如将文本设置为 textview,所以这不是问题。我的问题是如何解析 HTML 代码以使内容按顺序显示?
我能想到的唯一方法是将 html 拆分为行,然后检查它是图像 URL 还是文本。然后我会使用 Jsoup 解析并放入各自的视图中。
String[] parts = htmlText.split(System.getProperty("line.separator"));
for(int i = 0; i<parts.length;i++){
if(parts[i].contains("<img src=\"")){
Document doc = Jsoup.parse(parts[i]);
String imgSrc = doc.getElementsByTag("img").attr("src");
//function to convert imageUrl to imageView
converttoImageView(imgSrc);
}
else{
Document doc2 = Jsoup.parse(parts[i]);
converttoTextView(doc2.text());
}
}
private void converttoTextView(String text){
View messageView = LayoutInflater.from(((PostViewHolder) holder).message_row.getContext()).inflate(R.layout.reply_message, ((PostViewHolder) holder).message_row, false);
TextView message_textview = (TextView) messageView.findViewById(R.id.reply_message);
message_textview.setText(text);
((PostViewHolder) holder).message_row.addView(messageView);
}
这样做的问题是,每个文本都是逐行分隔的,并且一旦调用该函数,就会动态创建文本视图。我想让 textview 可选择,以便用户可以复制和粘贴。但我无法选择整个文本。我只能为每个 textview 选择 textview。
我得到的输出
<TextView> Hello how are you today</TextView>
<TextView> I am fine thank you </TextView>
<ImageView>testing.jpg</ImageView>
<TextView>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</TextView>
<TextView>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</TextView>
<ImageView>testing2.jpg</ImageView>
预期输出
<TextView> Hello how are you today \n\n I am fine thank you </TextView>
<ImageView>testing.jpg</ImageView>
<TextView>Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s.</TextView>
<ImageView>testing2.jpg</ImageView>
【问题讨论】:
标签: android parsing textview jsoup