2017-04-01 77 views
-1

我有一个应该包含图像按钮的自定义适配器。但是,我对getView()方法的覆盖实现感到困惑。由于我的图像按钮是动态定义的,我能够通过使用代码如何动态定义项目时创建自定义阵列适配器

@Override 
public View getView(int i, View view, ViewGroup viewGroup){ 
    ImageButton ibutton = (ImageButton) getItem(i); 

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

当我尝试使用getView()时,出于某种原因,imagebutton不可点击。

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

回答

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 ; 
    } 

} 
+0

谢谢,这个作品。我不知道ImageButton本身可以作为视图返回。 – kmindspark

+0

对不起,实际上,当我尝试使用getView方法时,imagebuttons由于某种原因没有显示出来。你知道为什么吗? (我现在注释了布局参数线)我更新了原始问题,还有另一个问题,即图像按钮不能被点击。 – kmindspark

+1

您是否尝试在图像按钮上设置clickListener,如下所示:imageButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Log.e(“position”,“position” + position); } }); –