我尝试使用RecyclerView显示左侧有图像,右侧有标题的列表。
通过for
循环,我在ArrayList中添加了Title和image
String[] mtitles = {"Title","Title","Title","Title","Title","Title","Title","Title","Title","Title"};
int[] mimages = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
List<Feed> items = new ArrayList<Feed>();
Feed feed = new Feed();
for (int i=0;i<mtitles.length;i++)
{
feed.setImage(mimages[i]);
feed.setTitle(mtitles[i]);
items.add(feed);
}
adapter = new MyAdapter(items);
这是我的Feed.class
public class Feed {
String title;
int image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<Feed> items;
public static class ViewHolder extends RecyclerView.ViewHolder
{
public ImageView icon;
public TextView title;
public ViewHolder(View v)
{
super(v);
icon = (ImageView)v.findViewById(R.id.imageView);
title = (TextView)v.findViewById(R.id.textView);
}
}
public MyAdapter(List<Feed> items)
{
this.items=items;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.icon.setImageResource(items[position]); // Problem here
}
@Override
public int getItemCount() {
return items.size();
}
}
在这一行,
holder.icon.setImageResource(items[position]);
我收到错误。
Array type expected;found.
屏幕截图:
答案 0 :(得分:2)
使用
holder.icon.setImageResource(items.get(position).getImage());
由于items
是List
个{0}}类对象,而不是Feed
。
答案 1 :(得分:1)
[]
索引表示法仅适用于数组。 List
有一个get
方法:items.get(position)
答案 2 :(得分:-1)
进行如下编辑:
public void onBindViewHolder(ViewHolder holder,int position){
tempValue=null; // this is an object of Feed class
tempValue = ( Feed ) items.get( position );
holder.icon.setImageResource(tempValue.getImage()); // try thishere
}