gpt4 book ai didi

java - 仅可绘制的 ListView

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:52 25 4
gpt4 key购买 nike

我有一个动态的可绘制对象数组,并希望将它们显示在可滚动列表中。我最遇到麻烦的是阵列适配器。这段代码没有出现任何编译时错误,但我得到的运行时错误是 -

Process: com.example.michael.myandroidappactivity, PID: 12297
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

但我不想使用 TextView !这是主要代码-

public class cards extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_old_cards);
ListView list = (ListView)findViewById(R.id.showCardList);
cardPile tmp = cardPile.getInstance();
ArrayList<Integer> discardPile = tmp.getDiscardPile();
ArrayAdapter<Integer> imgAdapt = new ArrayAdapter<Integer>(this,R.layout.listview_layout,discardPile);
list.setAdapter(imgAdapt);
}

}

最佳答案

您必须创建一个新类来扩展 BaseAdapter界面并修改getView方法返回您想要在 ListView 中显示的 View 。例如:

public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Integer> imagesIds;

public ImageAdapter(Context _context, ArrayList<Integer> _imageIds)
{
context = _context;
imageIds = _imageIds;
}


@Override
public int getCount()
{
return imgIds.size();
}

@Override
public Object getItem(int position)
{
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView view;

if( convertView != null ) // recycle call
{
view = (ImageView) convertView;
}
else
{
view = new ImageView(context);
image.setBackgroundResource(imageIds.get(position));
}

return view;
}
}

然后将您的 listView 适配器修改为:

list.setAdapter( new ImageAdapter( this, discardPile) );

关于java - 仅可绘制的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25464869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com