Skip to content

Instantly share code, notes, and snippets.

@ixiyang
Created November 4, 2013 07:54
Show Gist options
  • Save ixiyang/7299433 to your computer and use it in GitHub Desktop.
Save ixiyang/7299433 to your computer and use it in GitHub Desktop.
adapter填充不同类型的数据以及不同的视图
public class MenuAdapter extends BaseAdapter {
public interface MenuListener {
void onActiveViewChanged(View v);
}
private Context mContext;
private List<Object> mItems;
private MenuListener mListener;
private int mActivePosition = -1;
public MenuAdapter(Context context, List<Object> items) {
mContext = context;
mItems = items;
}
public void setListener(MenuListener listener) {
mListener = listener;
}
public void setActivePosition(int activePosition) {
mActivePosition = activePosition;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return getItem(position) instanceof Item ? 0 : 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean isEnabled(int position) {
return getItem(position) instanceof Item;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Object item = getItem(position);
if (item instanceof Category) {
if (v == null) {
v = LayoutInflater.from(mContext).inflate(R.layout.menu_row_category, parent, false);
}
((TextView) v).setText(((Category) item).mTitle);
} else {
if (v == null) {
v = LayoutInflater.from(mContext).inflate(R.layout.menu_row_item, parent, false);
}
TextView tv = (TextView) v;
tv.setText(((Item) item).mTitle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tv.setCompoundDrawablesRelativeWithIntrinsicBounds(((Item) item).mIconRes, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(((Item) item).mIconRes, 0, 0, 0);
}
}
v.setTag(R.id.mdActiveViewPosition, position);
if (position == mActivePosition) {
mListener.onActiveViewChanged(v);
}
return v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment