我想动态添加从布局 XML 膨胀的项目列表LinearLayout
到ScrollView
. findViewById
这涉及为每个项目多次调用,我被告知这是非常昂贵的。我怎样才能回收我的观点来避免这种情况?
我会使用ListView
, 除了每个项目中可以包含任意数量的内容和评论元素,而且我在Google I/O 2010 - ListView 的世界中被告知ListView
s 不应该过于复杂。
这是我的相关方法的代码:
private void addQuotes(NodeList quoteNodeList){
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(int i = 0; i < quoteNodeList.getLength(); i++){
Log.i(getClass().getSimpleName(), "Adding quote number " + i);
Node quoteNode = quoteNodeList.item(i);
// Inflate view to hold multiple content items, single additional content TextView, and multiple comment items
LinearLayout quote = (LinearLayout) layoutInflater.inflate(R.layout.quote, null);
LinearLayout contentList = (LinearLayout) quote.findViewById(R.id.dialog_list);
TextView additionalContent = (TextView) quote.findViewById(R.id.additional_content);
LinearLayout commentList = (LinearLayout) quote.findViewById(R.id.comment_list);
// Get data for content items and add to contentList
NodeList contentNodeList =
XmlUtilities.getChildWithTagName(quoteNode, NetworkHelper.XML_TAG_QUOTE_CONTENT).getChildNodes();
for(int contentIndex = 0; contentIndex < contentNodeList.getLength(); contentIndex++){
Log.i(getClass().getSimpleName(), "Adding content number " + contentIndex + " to quote number " + i);
Node contentItemNode = contentNodeList.item(contentIndex);
// Inflate view to hold name and dialog TextViews
LinearLayout contentItem = (LinearLayout) layoutInflater.inflate(R.layout.dialog_item, null);
TextView nameView = (TextView) contentItem.findViewById(R.id.speaker);
TextView dialogView = (TextView) contentItem.findViewById(R.id.dialog);
// Get data and insert into views
String nameString = XmlUtilities.getChildTextValue(contentItemNode, NetworkHelper.XML_TAG_QUOTE_CONTENT_ITEM_NAME);
String dialogString = XmlUtilities.getChildTextValue(contentItemNode, NetworkHelper.XML_TAG_QUOTE_CONTENT_ITEM_DIALOG);
nameView.setText(nameString + ":");
dialogView.setText("\"" + dialogString + "\"");
// Add to parent view
contentList.addView(contentItem);
}
// Get additional content data and add
String additionalContentString = XmlUtilities.getChildTextValue(
quoteNode, NetworkHelper.XML_TAG_QUOTE_ADDITIONAL_CONTENT);
Log.d(getClass().getSimpleName(), "additionalContentString: " + additionalContentString);
additionalContent.setText(additionalContentString);
// TODO: Get comment data and add
// Add everything to ScrollView
mQuoteList.addView(quote);
Log.d(getClass().getSimpleName(), "additionalContent: " + additionalContent.getText());
}
参数quoteNodeList
是一个org.w3c.dom.NodeList
。
XmlUtilities
是我自己编写的辅助类,但方法应该是不言自明的。
任何帮助深表感谢。