![](/img/trans.png)
[英]Passing data for list view from Asynctask to a custom list adapter class
[英]Custom Class in List Adapter
我在理解范围如何影响我的代码时遇到了一些麻烦。 我似乎无法访问公共类的公共属性。
我创建了一个自定义类ArtistPacket
,该类具有要发送到自定义适配器( ArtistListAdapter
)的信息块。
自定义类如下:
public class ArtistPacket{
public String name;
public int id;
public ArtistPacket(String name, int id){
this.name = name;
this.id = id;
}
}
它在MainActivityFragment
中定义,在这里我创建一个ArtistListAdapter
这些ArtistPackets
。
public class MainActivityFragment extends Fragment{
...
ArtistListAdapter<ArtistPacket> artistListAdapter =
new ArtistListAdapter<ArtistPacket>(getActivity(), artistData);
...
然后,我定义ArtistListAdapter
和getView
private class ArtistListAdapter<ArtistPacket> extends ArrayAdapter<ArtistPacket>{
public ArtistListAdapter(Context context,ArrayList<ArtistPacket> artists){
super(getActivity(),0,artists);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
...
在getView
,我需要ArtistPacket
对象(在本例中为artist
)的name
和id
。 所以我尝试打电话
ArtistPacket artist = getItem(position);
textItemContent.setText((CharSequence) artist.name);
但是我得到一个编译错误。 在调试器中,看起来好像是整个对象都通过了-似乎适配器不访问name
或id
属性。
我得到的错误是:
Error:(98, 58) error: cannot find symbol variable name
where ArtistPacket is a type-variable:
ArtistPacket extends Object declared in class
MainActivityFragment.ArtistListAdapter
我的实现范围存在问题吗? 如果适配器在调试器中清楚可见,为什么适配器不能看到ArtistPacket
对象的内容?
这是完整的getView:
@Override
public View getView(int position, View view, ViewGroup parent) {
// Find the artist packet at a given position
ArtistPacket artist = getItem(position);
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
TextView textItemContent = (TextView) view.findViewById(R.id.list_item_content);
ImageView imageViewContent = (ImageView) view.findViewById(R.id.list_item_image);
textItemContent.setText((CharSequence) artist.name);
imageViewContent.setImageResource(artist.id);
return view;
}
微妙而重要的答案。
下面的类定义:
private class ArtistListAdapter<ArtistPacket> extends ArrayAdapter<ArtistPacket>
可以分解以更好地理解。
ArtistListAdapter<ArtistPacket>
表示ArtistListAdapter
将类型参数定义为ArtistPacket
。 这意味着只要引用了ArtistPacket,便会引用此类型声明-而不是上面定义的类。
另一方面,
extends ArrayAdapter<ArtistPacket>
表示ArtistListAdapter
扩展了一个使用上述ArtistPacket类的ArrayAdapter
。
换句话说,第一个<>与定义的类型有关,而第二个<>与已使用的类型有关。
因此,我使用了以下声明:
private class ArtistListAdapter extends ArrayAdapter<ArtistPacket>
这意味着ArrayAdapter
将使用ArtistListAdapter
类型ArtistPacket
不会通过定义其自身的本地ArtistPacket类型而混淆情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.