我已经使用RelativeLayout动态创建了按钮。现在我必须实现动态按钮的监听器。我怎么能这样做,另一件事我正在创建多个按钮,所以请告诉我该怎么做?
这是我的代码
public class CreateButton extends Activity {
int top=60,bottom=350, i;
int s = 1,iddelete = 1,idedit=1;
RelativeLayout rl;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rl = (RelativeLayout)findViewById(R.id.edit_r);
// Create Bed Room
Button Btn_BedRoom = (Button)findViewById(R.id.bed);
Btn_BedRoom.setOnClickListener(ListenrOf_BedRoom);
}
// Listener Of Create Bed Room
private OnClickListener ListenrOf_BedRoom = new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CreateRoom();
i+=35;
}
};
public void CreateRoom()
{
final Button delete = new Button(this);
delete.setText("delete");
delete.setBackgroundResource(R.drawable.cross);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(120, top+i, 0, bottom-i);
delete.setHeight(5);
delete.setWidth(5);
delete.setLayoutParams(lp);
delete.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CreateRoom();
}
});
rl.addView(delete);
Button BtnEdit = new Button(this);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(150,top+i,0,bottom-i);
BtnEdit.setBackgroundResource(R.drawable.edit);
BtnEdit.setHeight(5);
BtnEdit.setWidth(5);
BtnEdit.getRight();
BtnEdit.setLayoutParams(lp1);
rl.addView(BtnEdit);
TextView tv = new TextView(this);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.setMargins(180,top+i,0,bottom-i);
tv.setText("Bed Room " + s++);
tv.setLayoutParams(lp2);
rl.addView(tv);
};
}
答案 0 :(得分:4)
Button bt = new Button(this.getApplicationContext());
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
});
答案 1 :(得分:0)
只需为您创建的按钮调用setOnClickListener,然后传入所需的单击侦听器对象。
答案 2 :(得分:0)
您必须保留对这些按钮的引用,以便您可以在其上设置侦听器(setOnClickListener()
)。您当然可以设置相同的侦听器,但在这种情况下,请记住为每个按钮设置不同的ID(setId()
)。
答案 3 :(得分:0)
Button mybutton = new Button(this);
mybutton.setText("My Button");
mybutton.setOnClickListener(this);