这是我的答案。希望它能帮助别人。扩展HtmlTextView
为我们提供了使用string
格式添加新属性的机会。然后,android:text
和custom:text2
可以在定制HtmlTextView
内以编程方式连接。
1.如果您使用的是HtmlTextView 或TextView,请扩展它。
public class HtmlTextview extends HtmlTextView {
public HtmlTextview(Context context) {
super(context);
}
public HtmlTextview(Context context, AttributeSet attrs) {
super(context, attrs);
setupText(attrs);
}
public HtmlTextview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupText(attrs);
}
private void setupText(AttributeSet attrs) {
String htmlString = (String) this.getText();
String text2;
TypedArray attributeValuesArray = getContext().obtainStyledAttributes(attrs, R.styleable.concatenate, 0, 0);
try{
text2 = attributeValuesArray.getString(R.styleable.concatenate_text2);
} finally {
attributeValuesArray.recycle();
}
if(text2 != null && text2.length() > 0){
htmlString = htmlString + text2;
this.setHtmlFromString(htmlString, new HtmlTextView.RemoteImageGetter());
}
}
}
2. HtmlTextview属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="concatenate">
<attr name="text2" format="string"/>
</declare-styleable>
</resources>
3.在string.xml资源
<resources>
<string name="app_name">HtmlTry</string>
<string name="string_a">
<![CDATA[
<body>
<p>very long text. Can also formatted in <font color="#f44336">Html.</font></p>
</body>
]]>
</string>
<string name="string_b">
<![CDATA[
<body>
<p>This is string B</p>
</body>
]]>
</string>
</resources>
4.最后应用它的XML布局内。
<com.htmltry.HtmlTextview
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/string_b"
custom:text2="@string/string_a"
/>
最终的结果是:
你管理,使其工作? – Vucko
是的,但以另一种方式。通过扩展HtmlTextView。谢谢btw。 – Tuss
没问题,然后自己发布答案,如果其他人有同样的问题,他们可以看到解决方案。 – Vucko