Android 通过代码添加imageButtons

Android 通过代码添加imageButtons,android,listview,bitmap,android-custom-view,baseadapter,Android,Listview,Bitmap,Android Custom View,Baseadapter,我有一个基本适配器类,用于填充listview。一些内容在布局文件中定义,我还需要根据传递给基本适配器的int值动态添加一定数量的图像按钮。 obj是一个具有int值和位图数组列表的对象; 当我运行这段代码时,我会得到更多的图像按钮,而不是obj.value的值。 likePre_pics是位图数组列表的名称 有人能帮忙吗 public class News_Feed_BaseAdapter extends BaseAdapter{ @O

我有一个基本适配器类,用于填充listview。一些内容在布局文件中定义,我还需要根据传递给基本适配器的int值动态添加一定数量的图像按钮。
obj是一个具有int值和位图数组列表的对象; 当我运行这段代码时,我会得到更多的图像按钮,而不是obj.value的值。 likePre_pics是位图数组列表的名称 有人能帮忙吗

      public class News_Feed_BaseAdapter extends BaseAdapter{

                      @Override
       public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    LinearLayout linLayout =
    (LinearLayout)convertView.findViewById(R.id.like_preview_LinearLayout);

      for(int i=0; i< obj.value;i++)
      {
          ImageButton op= new ImageButton(context);

          LayoutParams lpView = new LayoutParams(100, 100);
            //op.setImageBitmap(obj.get(position).likePre_pics.get(i));

             linLayout.addView(op,lpView);

      }

                }
         }
public class News\u Feed\u BaseAdapter扩展BaseAdapter{
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//TODO自动生成的方法存根
线性布局=
(LinearLayout)convertView.findViewById(R.id.like\u preview\u LinearLayout);
对于(int i=0;i
从您的代码中可以看出,有两个问题,第一个是IndexOutOfBoundsException。ArrayList IndexOutOfBoundsException仅在您引用的项目较多/较少时发生。 //op.setImageBitmap(obj.get(position).likePre_pics.get(i)); 你注释掉的那行。您指的是obj.get(position),其中obj有obj.size()个元素

接下来是ImageButton问题,因为在将新ImageButton添加到convertview的linLayout中时,没有以有效的方式重用convertview,这就是为什么linLayout显示多于2个ImageButton的原因

例如:如果列表中有20项,则意味着getView将被调用20次。正如您将在android文档中发现的那样,convertView是一个旧视图,它被传递给您以供重用,每次传递给您时,您都会向其中添加更多的imagebutton。这就是imagebutton出现问题的原因


如果您感兴趣,请查看Romain Guy的google i/o演示文稿。

致命异常:main java.lang.IndexOutOfBoundsException:无效索引4,大小为4,位于java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255),位于java.util.ArrayList.get(ArrayList.java:308),位于com.example.foodshoot.News\u Feed\u BaseAdapter.getView(News_Feed_BaseAdapter.java:96)在android.widget.AbsListView.ActainView(AbsListView.java:2177)上,是哪个?你得到的图像按钮比预期的多,或者你的应用程序因上述错误而崩溃?如果我输入(int i=0;i