列表适配器中的自定义 Class

Custom Class in List Adapter

我无法理解作用域如何影响我的代码。我似乎无法访问 public class.

的 public 属性

我创建了一个自定义 class ArtistPacket,其中有一段信息我想发送到我的自定义适配器 (ArtistListAdapter)。

自定义class如下:

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 对象的 nameid(在本例中为 artist)。所以我试着打电话

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;
    }

对此的微妙而重要的回答。

以下class定义:

private class ArtistListAdapter<ArtistPacket> extends ArrayAdapter<ArtistPacket>

可以分解以便更好地理解。

ArtistListAdapter<ArtistPacket>

暗示 ArtistListAdapter 定义 类型参数为 ArtistPacket。这意味着无论何时引用 ArtistPacket,它都是在引用此类型声明 - 而不是上面定义的 class。

另一方面,

extends ArrayAdapter<ArtistPacket>

暗示 ArtistListAdapter 扩展 ArrayAdapter 使用 上述 ArtistPacket class.

换句话说,第一个 <> 是关于 defined 类型,而第二个 <> 是关于 used 类型。

因此,我使用了以下声明:

private class ArtistListAdapter extends ArrayAdapter<ArtistPacket>

这意味着 ArrayAdapter 将使用类型 ArtistPacket 扩展 ArtistListAdapter - 不会通过定义它自己的本地 ArtistPacket 类型来混淆情况。

Source