我創建了一個使用LayoutInflater的適配器arraylist,因此圖像保持了比例。我正在嘗試爲選定的項目標題執行簡單的敬酒,即「牛肉」。 寄託都workd如預期,除了我正在從土司的輸出,例如Toast已選中項目 - AdapterView/ArrayList
測試com.sweatboxbbq.www.sweatboxbbq.Kansas市$ MyAdaptor $ @項42aa9398
我知道我請求一個字符串值和我得到它,但從代碼,我無法弄清楚如何得到我想要的。 我只想捕捉標題,以便我可以將它敬酒(現在,然後最終做其他事)。
例items.add(new Item(beef, R.drawable.mine_beef));
我會得到「牛肉」
的字符串值,也許我可以莫名其妙的ID陣列,這些項目的冠軍的,並從那裏拉他們的onclick方法?下面
是我的Java代碼
public class KansasCity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kansas_city);
final GridView gridView = (GridView) findViewById(R.id.meat_choice);
gridView.setAdapter(new MyAdapter(this));
//on click starts here
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> MyAdapter, View v, int position, long id)
{
String flavorPicked = "" +
String.valueOf(MyAdapter.getItemAtPosition(position));
Toast.makeText(KansasCity.this, "Test " + flavorPicked,
Toast.LENGTH_LONG).show();
}
});
}
//gridview
public class MyAdapter extends BaseAdapter {
public List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
items.add(new Item("Beef", R.drawable.mine_beef));
items.add(new Item("Chicken", R.drawable.mine_chicken));
items.add(new Item("Swine", R.drawable.mine_pork));
items.add(new Item("Fish", R.drawable.mine_pork));
items.add(new Item("Turkey", R.drawable.mine_pork));
items.add(new Item("Sauce", R.drawable.mine_pork));
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return items.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = (Item) getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item {
final String name;
final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
}
感謝您的任何幫助。
謝謝你!你的救星!我將代碼更改爲'String flavorPicked =((KansasCity.MyAdapter.Item)MyAdapter.getItemAtPosition(position))。name;' 它工作! – Awatatah 2015-01-20 21:43:32