ArrayAdapter getView() 方法如何工作?
我想做一个 ArrayAdapter 来显示图像和文本。如果可能的话我不想举例。我希望有人向我解释 getView()
的工作原理。
谢谢。
I want to do an ArrayAdapter
to display an image and text. I don't want examples if possible. I'd like someone to explain me how getView()
works.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getView()
是适配器的主要部分。它返回将显示为列表/网格/画廊/任何使用适配器项目的视图的View
。当您滚动视图(例如列表)时它会触发。因此,您应该做的第一件事是创建自定义适配器。您可以从
BaseAdapter
扩展它。然后您需要创建一些要显示的数据(或从外部将其传递给适配器 - 这是更好的解决方案)。之后覆盖
getView()
方法并确保在那里返回您的自定义视图。在您的情况下,它应该是带有ImageView
和TextView
的Layout
(并且不要忘记填充它们)。您可以通过以下网址了解更多信息:
getView()
is the main part of your adapter. It returnsView
that will be displayed as your list/grid/gallary/any view that use adapter item. It triggers when you scroll the view(list for example).So the first thing you should do its to create your custom adapter. You may extend it from
BaseAdapter
. Then you need to create some data to display (or pass it to adapter from out side - its better solution).After that override
getView()
method and make sure to return your custom View there. In your case it should be aLayout
withImageView
andTextView
(and dont forget to fill them).You can learn more from :
在
BaseAdapter
中,您有getView
函数,该函数由AdapterView
即ListView
调用。您需要重写 BaseAdapter 的 getCount 方法以返回要显示的视图总数。
在 getView 中你会得到以下内容:
position:
每个位置都会每次显示时调用 getView。
转换视图
由于
getView
被多次调用,每次都生成一个新视图的成本很高,因此列表视图为您提供了以前创建的视图之一以供重复使用。父级
对此视图将成为其子级的父视图的引用。
ArrayAdapter
是BaseAdapter
的子类,它在构造函数中采用ArrayList
(或数组)。并为您覆盖
getCount
。所以你需要实现的是
getView
in
BaseAdapter
you havegetView
function that is called by for anAdapterView
i.e.ListView
.you need to override
getCount
method of the BaseAdapter to return total number of views to diplay.And in getView you get following things:
position:
getView going to be called for each position every time it is displayed.
convertView
As
getView
is call many times inflating a new view every time is expensive so list view provides you one of the previously created view to re-use.parent
A reference to the parent view that this view will be a child of.
ArrayAdapter
is a subclass ofBaseAdapter
which takesArrayList
(or array) in constructor.And overrides
getCount
for you.So all you need to implement is
getView