我使用 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);
};
}
Button bt = new Button(this.getApplicationContext());
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
});