代码之家  ›  专栏  ›  技术社区  ›  Aman Aalam

有关ListView自定义行布局项的onclick()事件的帮助

  •  5
  • Aman Aalam  · 技术社区  · 15 年前

    我有一个listview,它的行由我格式化。每一行都混合了ImageView和TextView。 我还实现了自己的适配器,并且能够通过它绘制每一行。

    现在,我想要这样的东西-

    • 用户单击ImageView(不是行中的任何其他位置,但只有此ImageView应响应单击)
    • 我知道了图像视图被点击的行的位置。

    为此,我做了很多尝试,希望我的代码尽可能高效(在过度杀戮方面)。 目前,我只能在特定的ImageView上捕获单击事件,但我不知道单击了哪一行。

    我在XML行中提供了这样的属性-

    <ImageView android:id="@+id/user_image"
        android:padding="5dip" 
        android:layout_height="60dip" 
        android:layout_width="60dip"
        android:clickable="true"
        android:onClick="uImgClickHandler"/> 
    

    在我的代码中,我有一个这样的方法:

    public void uImgClickHandler(View v){
      Log.d("IMG CLICKED", ""+v.getId());
      LinearLayout parentRow = (LinearLayout)v.getParent();
    
     }
    

    我可以得到父行(也许),但不确定如何从这里走得更远。 有人能帮忙吗?

    4 回复  |  直到 12 年前
        1
  •  14
  •   Labeeb Panampullan    15 年前

    请参考这个,
    我只是写代码给你个主意,格式不对

     class youaddaper extends BaseAdapter{
    
       public View getView(int position, View convertView, ViewGroup parent){
            LayoutInflater inflate = LayoutInflater.from(context);
            View v = inflate.inflate(id, parent, false);
    
          ImageView imageview = (ImageView) v.findViewById(R.id.imageView);
            imageview.setOnClickListener(new imageViewClickListener(position));
          //you can pass what ever to this class you want,
          //i mean, you can use array(postion) as per the logic you need to implement 
       }
       class imageViewClickListener implements OnClickListener {
       int position;
        public imageViewClickListener( int pos)
            {
                this.position = pos;
            }
    
        public void onClick(View v) {
          {// you can write the code what happens for the that click and 
           // you will get the selected row index in position
         }
    }
    

    }

    希望对你有帮助

        2
  •  1
  •   Andrea    12 年前

    另一种选择是使用这些方法 setTag() getTag() 的观点。在getview中设置如下:

    imageView.setTag(new Integer(position));
    

    然后在 onClick() 您可以通过以下方式找到标签:

    Integer tag = v.getTag();
    

    这将用于将图像视图关联到ListView项的位置。

    请注意,如果ListView可能会从中间丢失项,则此方法会产生问题,以便在ListView的生命周期内更改项位置。

        3
  •  0
  •   Devendra Singh    13 年前

    您可以这样做: 在适配器的getView方法中 按钮btn1=(button)convertview.findView byid(r.id.btn1); btn1.setonclicklistener(活动性);

    此外,您还可以在活动中处理onclick事件, 对于这里的活动上下文,mactivity只需在适配器的构造器中传递它,并将它强制转换到活动中,比如 myActivity mactivity=(myActivity)上下文; 在适配器中。 桑克斯

        4
  •  0
  •   Miki Habryn    12 年前

    这似乎适用于其项布局包含带有android:onclick=“editimage”的ImageView的ListActivity:

    public void editImage(View v) {
            int[] loc = new int[2];
            v.getLocationInWindow(loc);
            int pos = getListView().pointToPosition(loc[0], loc[1]);
            Cursor c = (Cursor) adapter.getItem(pos);
            // c now points at the data row corresponding to the clicked row
    }
    
    推荐文章