动态类型的arraylist和自定义适配器

时间:2017-01-10 08:26:26

标签: android android-adapter custom-adapter

我有类似的5级。每个班级" Code" ,"名称"属性。我使用自定义适配器列出它们,我想使用1适配器。这可能吗?

我在那里堵塞:holder.txtCode.setText(list.get(position).getCode()????);                  holder.txtName.setText(list.get(position).getName()?????);

public class AdapterCodeName extends BaseAdapter {
    private static ArrayList<?> list;
    private static ArrayList<?> listOrj;
    private static ArrayList<?> mOriginalValues;
    private LayoutInflater mInflater;
    public AdapterCodeName (Context context, ArrayList<?> results){
        list = results;
        listOrj = results;
        mInflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            convertView = mInflater.inflate(R.layout.row_code_name, null);
            holder = new ViewHolder();
            holder.txtCode = (TextView) convertView.findViewById(R.id.txtCode);
            holder.txtName = (TextView) convertView.findViewById(R.id.txtName);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        holder.txtCode.setText(list.get(position).getCode() ????);
        holder.txtName.setText(list.get(position).getName() ?????);

        return convertView;
    }
    static class ViewHolder{
        TextView txtCode,txtName;
    }

1 个答案:

答案 0 :(得分:0)

从一个类(接口)扩展所有类,并使用基类型/接口的对象列表创建适配器:

public interface Item {
    String getName();
    String getCode();
}


public class ListItem1 implements Item {
    private String name;
    private String code;

    @Override
    public getName() {
        return name;
    }

    @Override
    public getCode() {
        return code;
    }
}

public class ListItem2 implements Item {
    private String name;
    private String code;
    private String somethingElse;

    @Override
    public getName() {
        return name;
    }

    @Override
    public getCode() {
        return code;
    }
}
适配器中的

private static ArrayList<? extends Item> list;

@Override
public Item getItem(int i) {
    return list.get(i);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ...

    holder.txtCode.setText(list.get(position).getCode());
    holder.txtName.setText(list.get(position).getName());

    return convertView;
}