adapter和inflator在android中有什么用?
最佳答案
Inflator 用于加载布局资源。例如:
private class SMSAdapter extends CursorAdapter {
public SMSAdapter(Context context, Cursor c) {
super(context, c);
}
public SMSAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.i(TAG, "adapter -- new view");
View itemView = LayoutInflater.from(context).inflate(R.layout.sms_list_item, parent,false);
ViewHolder holder = new ViewHolder();
holder.who_tv = (TextView) itemView.findViewById(R.id.sms_who_tv);
holder.content_tv = (TextView) itemView.findViewById(R.id.sms_content_itv);
holder.time_tv = (TextView) itemView.findViewById(R.id.sms_time_tv);
itemView.setTag(holder);
return itemView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Log.i(TAG, "adapter -- bind view");
final ViewHolder holder = (ViewHolder) view.getTag();
holder.who_tv.setText("来自:");
holder.who_tv.append(cursor.getString(cursor.getColumnIndexOrThrow("address")));
holder.content_tv.setText(cursor.getString(cursor.getColumnIndexOrThrow("body")));
holder.time_tv.setText(Tools.date2str(new Date(cursor.getLong(cursor.getColumnIndexOrThrow("date")))));
//根据类型,设置背景
int type = cursor.getInt(cursor.getColumnIndexOrThrow("type"));
final LinearLayout.LayoutParams params = (LayoutParams) holder.content_tv.getLayoutParams();
if(2 == type) {
holder.content_tv.setBackgroundResource(R.drawable.chatfrom_bg);
params.gravity = Gravity.LEFT;
} else {
holder.content_tv.setBackgroundResource(R.drawable.chatto_bg);
params.gravity = Gravity.RIGHT;
}
}
class ViewHolder {
TextView who_tv;
TextView time_tv;
TextView content_tv;
}
}
关于android - 适配器和充气机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037906/