当触摸其中的按钮时,如何获取ListView单元格的位置?

时间:2012-11-15 05:59:58

标签: java android eclipse android-listview

以下是Button中每个单元格中ListView的一些XML:

android:onClick="buttonTouched"

这就是我的ListActivity上调用的内容:

public void buttonTouched(View v) 
{
    // how do I get the "position" of the cell this view is on?
}

如何获取触摸按钮的单元格position

3 个答案:

答案 0 :(得分:0)

在你的适配器中试试这个:

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    View row = convertView;
    YourWrapper wrapper = null;

    if (row == null)
    {
        row = inflater.inflate(R.layout.layout, parent, false);
        wrapper = new YourWrapper (row);
        row.setTag(wrapper);
    }
    else
        wrapper = (YourWrapper) row.getTag();

    wrapper.getButton().setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // What you want
        }
    });

    return row;
}

答案 1 :(得分:0)

由于我在同一行上有多个按钮,我最后只是在我的适配器中将标签设置为所需的位置,然后按下按钮触摸标签:

public void imageClick(View v) 
{
    int position = (Integer) v.getTag();
}

我走这条路的原因是因为我需要在ListActivity中完成点击以访问我需要的那些不在适配器中的数据。

答案 2 :(得分:0)

请看一下:OnItemClickListener。实施示例:setOnItemClickListener on custom ListView

由于列表视图的每一行都有3个按钮,并且你有3个diff实现,所以还有另一种方法。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;

    if(null == convertView){
        holder = new ViewHolder();
        convertView = inflater.inflate(LAYOUT_RESOURCE, null);
        holder.btn1 = (Button) convertView.findViewById(R.id.btn1);
        holder.btn2 = (Button) convertView.findViewById(R.id.btn2);
        holder.btn3 = (Button) convertView.findViewById(R.id.btn3);
        //setting tag to reduce hierarchy lookup
        convertView.setTag(holder);
    } else {
        //getting tag to obtain the already found views
        holder = (ViewHolder) convertView.getTag();
    }
    //Updating fields
    holder.btn1.setOnClickListener(commonListener); 
    holder.btn2.setOnClickListener(commonListener); 
    holder.btn3.setOnClickListener(commonListener); 
    //returning the populated view
    return convertView;
}

OnClickListener commonListener = new OnClickListener(){

    @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.btn1:
                //do your work
                break;
            case R.id.btn2:
                //do your work
                break;
                case R.id.btn3:
                //do your work
                break;
                default:
                break;
            }
        }
    }); 
/**
 * Holder class to improve performance. Helps in reducing the lookup for
 * views.
 * 
 */
private static class ViewHolder {

    Button btn1;
    Button btn2;
    Button btn3;
}

希望这有帮助。