android - 适配器和充气机

标签 android

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/

相关文章:

android - Activity 已泄漏最初在此处添加的窗口

android - AppCompatActivity 中未触发 onBackPressed() 方法

android - 将一个圆圈分成不同的区域作为飞镖盘?

java - 获取 EditText 背景资源

android - 是否可以在 HoneyComb 之前在 App Widget 中使用 Collections

android - 在 Android 市场中以编程方式检查我的应用程序版本

java - 如何将 android 项目作为库导入而不是将其编译为 apk (Android studio 1.0)

c++ - Android NDK 有 sleep() 函数吗?

android - 用户行走的折线

Android mediaplayer 音乐暂停有时不起作用