[英]Custom View with XML Layout in Android
我有一個ListAdapter,它有很多不同的行布局。 要擁有一個干凈的代碼,我想從View類中的適配器的getView()外包行的布局。 是否可以將XML布局擴展為自定義視圖? 我只找到了LayoutInflater,但它返回了一個View,但沒有幫助。 我想要一個類似於Activity的setLayout()的東西。 這可能嗎?
謝謝!
您可以擁有自定義行視圖並在其構造函數中為您的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
元素會將其子項添加為自定義視圖的子項。 查看合並布局了解更多信息。
我還使用了一個自定義適配器和一個視圖,如:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.