如何为 Android 的 ListView 中的菜单项创建图标?
我正在使用 ListView
来显示应用程序的主屏幕。
主屏幕本质上是一个进入应用程序不同部分的菜单
。 目前,我有 ListView
,其内容是在 onCreate
方法中以编程方式添加的。
下面是执行此操作的代码片段:
String[] mainItems = {
"Inbox", "Projects", "Contexts", "Next Actions"
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mainItems));
registerForContextMenu(getListView());
}
因此,菜单本质上只是一堆节点,其文本包含在 mainItems 数组中。 我知道我可以创建一个包含 ImageView 和 TextView 的 XML 布局(即 R.layout.mainMenu_item
),但我不确定如何设置 ImageView 的图标。 我已经看到有一个 setImageResouce(int resId) 方法,但是在使用 ArrayAdapter 生成时使用它的方法却让我困惑。 有一个更好的方法吗?
I am using a ListView
to display the main screen of my application.
The main screen is essentially a menu
to get into the different sections of application. Currently, I have the ListView
whose contents are added programmatically in the onCreate
method.
Here is the code snippet that does this:
String[] mainItems = {
"Inbox", "Projects", "Contexts", "Next Actions"
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mainItems));
registerForContextMenu(getListView());
}
So the menu is essentially just a bunch of nodes with the text contained in the mainItems array. I know that I can create an XML layout (i.e. R.layout.mainMenu_item
) that has an ImageView and TextView in it, but I am unsure how to set the ImageView's icon. I have seen that there is a setImageResouce(int resId) method, but the way to use this when generating with an ArrayAdapter is eluding me. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常对 ListView 所做的事情是通过扩展方便的 BaseAdapter 类来实现我自己的 Adapter。 正如前面的海报所提到的,您将实现的抽象方法之一是 getView()。 从那里,您可以膨胀包含 ImageView 的布局,使用 findViewById 获取对其的引用,并将图像设置为您添加到资源中的任何可绘制对象。
What I typically do for a ListView is to implement my own Adapter by extending the handy BaseAdapter class. One of the abstract methods you'll implement will be getView() as the previous poster mentioned. From there you can inflate a layout containing an ImageView, get a reference to it using findViewById, and set the image to whatever drawable you've added into your resources.
来自 ArrayAdapter 的谷歌文档。
From the google docs for ArrayAdapter.