如何使用Android TagHandler读取自定义html标签属性



我正在扩展Android TagHandler类来处理TextField中的自定义html标记。到目前为止,我已经能够拦截这些标签,并将自定义功能添加到这些标签的"onClick()"中。然而,我无法捕获这些自定义标签的任何属性,例如:

"This is an example of a custom mark-up tag embedded in text that a text field would handle <custom id='1233' uri='0023'> CUSTOM </custom>and that I need to capture."

我能够捕捉自定义标签的出现,但不能捕捉以下属性:

public class SpecialTagHandler implements TagHandler
{
@Override
public void handleTag(
boolean opening,
String tag,
Editable output,
XMLReader xmlReader)
{
if(tag.equalsIgnoreCase("custom")) {
// handle the custom tag
if(opening) {
Log.e(TAG, "found custom tag OPENING");
try {
Field elementField = xmlReader.getClass().getDeclaredField("theNewElement");
elementField.setAccessible(true);
try {
Object element = elementField.get(xmlReader);
Field attsField = element.getClass().getDeclaredField("theAtts");
attsField.setAccessible(true);
Object atts = attsField.get(element);
Field dataField = atts.getClass().getDeclaredField("data");
dataField.setAccessible(true);
String[] data = (String[])dataField.get(atts);
Field lengthField = atts.getClass().getDeclaredField("length");
lengthField.setAccessible(true);
int length = (Integer)lengthField.get(atts);
String mIdAttribute = null;
String mUrlAttribute = null;
for(int i = 0; i < length; i++) {
if("id".equals(data[i*5 + 1])) {
mIdAttribute = data[i*5 + 4];
} else if("uri".equals(data[i*5 + 1])) {
mUrlAttribute = data[i*5 + 4];
}
}
Log.e(TAG, "id: " + mIdAttribute + " url: " + mUrlAttribute);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
}
}
}
}

关于如何读取id和uri属性,有什么建议吗?曾讨论过如何使用传递给该函数的XMLReader。提前感谢!

--------有答案了!--------

好吧,再挖一挖,沃伊拉!是-您确实可以在标记的html文本中访问标记中的自定义属性。我必须包含@rekire使用反射访问xmlReader属性的黑暗魔法。(这些元素都不是"肉眼可见"的)。链接在这里:链接。不需要求助于重复的java类或时髦的标签名称,这些名称实际上包括id!再次感谢-@rekire添加了从链接帖子中转述的代码,这将起到作用。

通过用自己的ContentHandler替换xmlReaderContentHandler,可以挂接到XMLReader并获取访问属性。此方法不适用于第一个html标记,因此必须在开始时添加一个伪标记。请参阅详细答案。

最新更新