开发者

Adapter and inflater

What is use开发者_如何学JAVA of Adapter and inflator in android?


Inflator is used to load a layout resources. for example:

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;
    }
}


Simple Difference between Adapter & Inflator

ADAPTER : It acts as abridge between Data and view,its also responsible to populate the views

INFLATOR : It helps in customizing Layout/Views


In my experience Inflater is used to initiate a layout: e.g:

   public class ProfileFragment extends Fragment{

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.profile,container, false);
    return rootView;
}}

Adapter: Adapter basically connects the Data to a View. Let's say if you have a list and you want to populate it with Items, the adapter is in charge of the populating. example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜