[英]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.