我有一個ListAdapter,它有很多不同的行佈局。要獲得乾淨的代碼,我想在View類的適配器的getView()中外包行的佈局。是否可以將XML佈局充填到自定義視圖中?我只找到了LayoutInflater,但它返回一個視圖,並沒有幫助。我想要一個Activity的setLayout()。這可能嗎?在Android中使用XML佈局的自定義視圖
謝謝!
我有一個ListAdapter,它有很多不同的行佈局。要獲得乾淨的代碼,我想在View類的適配器的getView()中外包行的佈局。是否可以將XML佈局充填到自定義視圖中?我只找到了LayoutInflater,但它返回一個視圖,並沒有幫助。我想要一個Activity的setLayout()。這可能嗎?在Android中使用XML佈局的自定義視圖
謝謝!
你可以有一個自定義列視圖,並誇大你的XML在它的構造:
public MyRow extends LinearLayout {
public MyRow(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.my_row, this, true);
... other initialization ...
}
}
和然後在my_row.xml
中使用merge
:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
... your row layout ...
</merge>
merge
元素會將其子元素添加爲自定義視圖的子元素。查看Merging Layouts以獲取更多信息。
謝謝,這解決了我的問題! – dbrettschneider 2011-04-04 07:13:27
我試過這個,得到錯誤'合併只能用於有效的視圖組root和attachtoroot = true'。 爲什麼? 我正在使用exatcly相同的調用,我正在使用一個xml合併作爲根,沒有屬性。 – 2012-12-25 12:55:00
該鏈接現在是404。我能找到的最接近的是http://developer.android.com/training/improving-layouts/reusing-layouts.html,但我也建議閱讀http://android-developers.blogspot.ca/2009/03/。 Android的佈局技巧-3-優化,by.html – Chani 2013-11-29 18:41:26
我alwas使用自定義適配器,具有像viewholder:
public class CalendarAdapter extends BaseAdapter {
protected static CalViewHolder holder;
private LayoutInflater mInflater;
public HashMap<Integer,String[]> appointments = new HashMap<Integer,String[]>();
public CalendarAdapter(Context context,HashMap<Integer,String[]> set_appointments) {
// Cache the LayoutInf
mInflater = LayoutInflater.from(context);
appointments = set_appointments;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return appointments == null ? 0:appointments.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.xml.appointment, null);
holder = new CalViewHolder();
holder.app_lay = (LinearLayout) convertView.findViewById(R.id.appointment_layout);
holder.app_head = (TextView) convertView.findViewById(R.id.appointment_head);
holder.app_body = (TextView) convertView.findViewById(R.id.appointment_body);
convertView.setTag(holder);
}else{
holder = (CalViewHolder) convertView.getTag();
}
holder.app_head.setText(appointments.get(position)[0]);
holder.app_body.setText(appointments.get(position)[1]);
return convertView;
}
static class CalViewHolder {
LinearLayout app_lay;
TextView app_head;
TextView app_body;
}
}
我也使用這種方法,但我有很多不同的行佈局,所以有一個非常大的「如果其他」。 – dbrettschneider 2011-04-04 07:12:28
有很多不同的佈局,性能會下降,我意識到有一個類似的Listview與多達六個不同的持有者,這是可以接受的,但請記住,如果您添加或刪除控件,您必須重新加載每一個項目。也許一個listview並不是你真正需要的,想想把你的視圖簡單地添加到一個LinearLayout中。 – 2red13 2011-04-04 07:27:46
找不到你。你能以更好的方式解釋......? – 2011-04-04 07:05:23
如果你喜歡馬修威利斯的回答,你可能會理解我的問題。 – dbrettschneider 2011-04-04 07:14:53