簡體   English   中英

列表適配器中的自定義類

[英]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);

...

然后,我定義ArtistListAdaptergetView

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 )的nameid 所以我嘗試打電話

ArtistPacket artist = getItem(position);    
textItemContent.setText((CharSequence) artist.name);

但是我得到一個編譯錯誤。 在調試器中,看起來好像是整個對象都通過了-似乎適配器不訪問nameid屬性。

我得到的錯誤是:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM