【发布时间】:2015-07-01 16:01:16
【问题描述】:
我在理解范围如何影响我的代码时遇到了一些麻烦。我似乎无法访问公共类的公共属性。
我创建了一个自定义类 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 对象的name 和id(在本例中为artist)。所以我试着打电话
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 对象在调试器中清晰可见,为什么 Adapter 看不到它的内容?
这是完整的 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;
}
【问题讨论】:
-
您是从艺术家列表中提取 ArtistPacket 实例吗?
-
你能展示一下你是如何创建对象
artist的吗? -
你能发布整个 getView 吗?你得到什么样的错误
-
我认为 ArtistPacket 是从
getItem(position)方法中提取的,并且正确的对象显示在调试器中。我认为范围有问题?编译器允许我按照我认为合适的方式操作对象 - 只是无法访问它的属性。
标签: java android oop listadapter