【问题标题】:Inside an Adapter for listview, there's an issue with button click listener在列表视图的适配器内,按钮单击侦听器存在问题
【发布时间】:2012-01-15 04:54:48
【问题描述】:
public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

//   new method
    private ListView listView;
    private AsyncImageLoader asyncImageLoader;
     private ImageAndText imageAndText;

//constructor
public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts) {
    super(activity, 0, imageAndTexts);


    asyncImageLoader = new AsyncImageLoader();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Activity activity = (Activity) getContext();


    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Load the image and set it on the ImageView


    //new method
    // Inflate the views from XML
    View rowView = convertView;
    ViewCache viewCache;

    if (rowView == null) {
        LayoutInflater inflater = activity.getLayoutInflater();
        rowView = inflater.inflate(R.layout.image_and_text_row, null);
        viewCache = new ViewCache(rowView);
        rowView.setTag(viewCache);
    } else {
        viewCache = (ViewCache) rowView.getTag();
    }
    imageAndText = getItem(position);

    Button btn2=(Button) findViewById(R.id.button1);

      btn2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                     //...........
               }
      });

这个适配器是给ListView的,它接受image_and_text_row.xml,代表listview的行数据。当我为 btn2 设置点击侦听器时,程序崩溃了。如果监听器被删除,那么程序运行正常。

问题是为什么适配器在代码中不能有按钮点击监听器?

【问题讨论】:

  • Jason,您绝对可以在适配器中安装点击监听器。您的问题应该在您的 logcat 中。甚至将其发布在这里也可能会有所帮助。
  • 你遇到了什么异常?

标签: android listener adapter


【解决方案1】:

只是在黑暗中拍摄:但是您的行Button btn2=(Button) findViewById(R.id.button1); 指的是适配器所在的ListActivity 或ListView。因此,R.id.button1 不存在...

您是否尝试过:Button btn2=((Button)rowView.findViewById(R.id.button1)); 这可能是您的问题(也就是说,无法看到您的 logcat)。 findViewById() 找到孩子。原始语句将查找 Activity 或 View 的子项。这个新语句将找到 rowView 的子项。

当然,这是一个假设,因为您没有完整地描述应用程序或问题,我必须根据我们掌握的信息假设每一行都有一个按钮。

希望对你有帮助,

模糊逻辑

P.S.希望你能明白如果缺乏相关信息,你会得到这样一个伪劣的答案。一个好的指南是:1)发生了什么? 2) 你预计会发生什么? 3)您的调试资源表明什么? 4) 我们需要了解哪些补充研究或概念?这些会导致更长的问题,但它们肯定更有效,由此得出的答案也是如此。

【讨论】:

  • 好的,没错,通过rowView.findById修复它找不到View。
【解决方案2】:

您应该做的是将 onClick 添加到按钮所在的 xml 文件中。 还要确保您的按钮位于您正在膨胀的相同布局内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2015-07-31
    相关资源
    最近更新 更多