类的这一个部分是网格视图的适配器, 这里我们能够只做相对很小的修改实现对来自主菜单代码本身的重用. 我们也能够适配布局文件,因此保持UI在视觉上的一致性具有无需重头开始,只要轻松的对代码进行回收利用这中好处. 你之前可能已经意识到了,我也重用了 OrderViewDialogue, 这事我志气啊为购物车写的一个类,但是在这里也能起作用.
/**
* SearchAdapter to handle the grid view of found items. Each grid item contains
* a view_grid_item which includes a image, name, and price.
*/
class SearchAdapter extends BaseAdapter {
private Vector<com.example.restaurant.MenuFactory.MenuItem> mFoundList;
private LayoutInflater inflater;
public SearchAdapter(Context c, Vector<com.example.restaurant.MenuFactory.MenuItem> list) {
mFoundList= list;
inflater = LayoutInflater.from(c);
}
public int getCount() {
return mFoundList.size();
}
public Object getItem(int position) {
return mFoundList.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new ItemView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ImageView picture;
TextView name;
TextView price;
if(v == null) {
v = inflater.inflate(R.layout.view_grid_item, parent, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.grid_name, v.findViewById(R.id.grid_name));
v.setTag(R.id.grid_price, v.findViewById(R.id.grid_price));
}
picture= (ImageView) v.getTag(R.id.picture);
name= (TextView) v.getTag(R.id.grid_name);
price= (TextView) v.getTag(R.id.grid_price);
final MenuItem foundItem = (MenuItem) mFoundList.get(position);
InputStream inputStream = null;
AssetManager assetManager = null;
try {
assetManager = getAssets();
inputStream = assetManager.open(foundItem.imageName);
picture.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (Exception e) {
Log.d("ActionBarLog", e.getMessage());
} finally {
}
name.setText(foundItem.name);
price.setText(foundItem.price);
return v;
}
}
}
代码示例 4 续