繁体   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