如何动态定义项目时创建自定义数组适配器

时间:2017-04-01 04:11:50

标签: java android android-studio view imagebutton

我有一个应该包含图像按钮的自定义适配器。但是,我对getView()方法的覆盖的实现有点困惑。由于我的图像按钮是动态定义的,因此我可以使用代码

恢复图像按钮
@Override
public View getView(int i, View view, ViewGroup viewGroup){
    ImageButton ibutton = (ImageButton) getItem(i);

如何返回其视图?我没有专门为它创建一个xml文件,因为它只是一个ImageButton(不与其他任何东西组合),但是有必要为它创建一个xml吗?或者有没有办法从图像按钮本身轻松获取视图。

当我为getView()尝试此操作时,由于某种原因,图像按钮不可单击。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageButton imageButton = getItem(position);
    return imageButton ;
}

1 个答案:

答案 0 :(得分:1)

尝试构建适合您的适配器:

public class ImageButtonAdapter extends BaseAdapter {
   private Context mContext;

   // Constructor
   public ImageButtonAdapter(Context c) {
      mContext = c;
   }

   public int getCount() {
      return listCount;
   }

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

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

   // create a new ImageButton for each item referenced by the Adapter
   public View getView(int position, View convertView, ViewGroup parent) {
      ImageButton imageButton ;

      if (convertView == null) {
         imageButton = new ImageButton (mContext);
         imageButton.setLayoutParams(lp);
      } 
      else 
      {
         imageButton = (ImageButton ) convertView;
      }
      imageButton.setBackgroundColor(Color.TRANSPARENT)
      return imageButton ;
   } 

}
相关问题