如何确定在android中点击了哪个动态按钮?

时间:2017-11-26 04:50:54

标签: java android

我在oncreate中创建了一个动态按钮,我没有在我的XML中放任何按钮。

LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);
Button btnAttendance,btnSched;
btnAttendance = new Button(this);
btnSched = new Button(this);
btnAttendance.setOnClickListener(this);
btnSched.setOnClickListener(this);
table.addView(btnAttendance);
        table.addView(btnSched);

//这是我在实现我的监听器时创建的OnClick方法:

@Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        BackgroundWorker fetchRiddles = new BackgroundWorker(DashActivity.this,"retrieveRiddles");
        switch (arg0.getId()) {
        case 1:  // in this case i usually put "R.id.Button1:" but my problem is that my buttons are dynamic
            fetchRiddles.execute("0,"+username);
            break;
        case 2:
            fetchRiddles.execute("1,"+username);
            break;
    }

如何确定使用开关点击了哪个按钮?我的按钮是动态创建的,不需要在我的xml中放任何按钮。

1 个答案:

答案 0 :(得分:0)

您可以通过编程方式设置ID:

btnAttendance = new Button(this);
btnAttendance.setId(100);
btnSched = new Button(this);
btnSched.setId(200);

然后比较:

@Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        BackgroundWorker fetchRiddles = new BackgroundWorker(DashActivity.this,"retrieveRiddles");
        switch (arg0.getId()) {
        case 100:  // in this case i usually put "R.id.Button1:" but my problem is that my buttons are dynamic
            fetchRiddles.execute("0,"+username);
            break;
        case 200:
            fetchRiddles.execute("1,"+username);
            break;
    }