我正在从字符串数组动态填充一个表。表的每一行也有一个加号和减号按钮来递增/递减一列的值。这些按钮也是动态创建的,如下面的代码所示。在这里,我如何能检测到准确的按钮点击。也就是说,如果我单击第二行的“+”按钮,如何获取单击按钮的ID以进行进一步处理。

 plusButton= new Button(this);
 minusButton= new Button(this);
 createView(tr, tv1, names[i]);
 createView(tr, tv2, (String)(names[i+1]));
 minusButton.setId(i);
 minusButton.setText("-");
 minusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
 plusButton.setId(i);
 plusButton.setText("+");
 plusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));`

最佳答案

您可以为每个按钮设置一个onClickListener侦听器。使用view.getId()方法中的按钮id来标识按钮单击。
您可以为每个按钮添加单独的侦听器,如下所示(假设为每个按钮设置的id对应于一行)

minusButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
             // Do some operation for minus after getting v.getId() to get the current row
        }
    }
);

编辑:
我想你的代码是这样的。如果有偏差,请纠正我。
Button minusButton = null;
for(int i = 0; i < rowCount; i++)
{
    minusButton = new Button(this);
    minusButton.setId(i);
    // set other stuff and add to layout
    minusButton.setOnClickListener(this);
}

让您的类实现接口onClick()并实现View.OnClickListener方法。
public void onClick(View v){
    // the text could tell you if its a plus button or minus button
    // Button btn = (Button) v;
    // if(btn){ btn.getText();}
    // getId() should tell you the row number
    // v.getId()
}

09-11 17:58
查看更多