程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> button-如何實現動態創建按鈕的監聽器?

button-如何實現動態創建按鈕的監聽器?

編輯:編程綜合問答
如何實現動態創建按鈕的監聽器?

我使用 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
    }
});
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved