【问题标题】:How to create custom array adapter when items defined dynamically动态定义项目时如何创建自定义数组适配器
【发布时间】:2017-04-01 04:11:50
【问题描述】:

我有一个自定义适配器,它应该包含图像按钮。但是,我对 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 ;
}

【问题讨论】:

    标签: java android android-studio view 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 ;
       } 
    
    }
    

    【讨论】:

    • 谢谢,这行得通。我不知道 ImageButton 本身可以作为视图返回。
    • 对不起,实际上,当我尝试使用 getView 方法时,由于某种原因,图像按钮没有显示出来。你知道为什么吗? (我现在注释掉了布局参数行)我还更新了原始问题,另一个问题是无法单击图像按钮。
    • 您是否尝试在图像按钮上设置 clickListener,如下所示: imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.e("position" ,"位置"+位置); } });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多