gpt4 book ai didi

java - Toast 项目选择 - AdapterView/ArrayList

转载 作者:行者123 更新时间:2023-11-30 11:09:39 26 4
gpt4 key购买 nike

我创建了一个使用 LayoutInflater 的 Adapter arraylist,以便图像保持比例。我正在尝试对所选项目标题(即“牛肉”)进行简单的 toast 。一切都按预期工作,除了我从 toast 中得到输出,例如

test com.sweatboxbbq.www.sweatboxbbq.Kansas City$MyAdaptor$Item@42aa9398

我知道我正在请求一个字符串值并且我得到了它,但是从代码中,我不知道如何得到我想要的。我只想捕获标题,这样我就可以把它干杯了(现在再做其他事情)。

示例 items.add(new Item( beef, R.drawable.mine_beef)); 我会得到一个字符串值“beef”

也许我可以通过某种方式识别这些数组项的标题,然后使用 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;
}



}


}

}

感谢您的帮助。

最佳答案

您可以覆盖 Item 类中的 toString() 并使其返回您要显示的字符串,或者使成员 name Item 公开,并像使用它一样

String flavorPicked = ((Item)MyAdapter.getItemAtPosition(position)).name;

关于java - Toast 项目选择 - AdapterView/ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com