如何在运行时创建多个按钮?+ Android

5
我写了下面的代码,但不知道如何为所有按钮编写OnclickListner()方法。
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative);
    for (int i = 1; i < 10; i++) {
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        Button b = new Button(this);
        b.setText(""+ i);
        b.setId(100+i);
        b.setWidth(30);
        b.setHeight(20);
        layout.addView(b, p);
    }
}
3个回答

2
您可以使用匿名内部方法来实现此操作:
Button b = new Button(this);
b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
    }
});
b.setText("" + i);
b.setTag("button" + i);
b.setWidth(30);
b.setHeight(20);

事实是我想为每个按钮单独编写SQLite查询。使用switch case更好吗?有10个按钮,每个按钮都有单独的查询。 - Pramod

0

如果你想让按钮执行不同的操作,你可以让你的Activity继承OnClickListener,然后在循环中设置b.setOnClickListener(this),并添加类似以下的代码:

@Override
public onClick(View v)
{
  // get who called by
  String sTag = (String) v.getTag();

  if (sTag.equals("button1"))
  {
    //do some stuff  
  }
  else if (sTag.equals("button2"))
  {
    //do some other stuff
  }
  // and so on
}

处理点击事件。


我在这里进行编辑,因为缺少换行符会使评论含糊不清:

int iBtnID = v.getId(); 
switch (iBtnID) 
{
  case 101: 
    // do stuff; 
    break; 
  case 102: 
    // do other stuff 
    break; 
  // and so on 
}

我正在使用setId()而不是标签,您能用switch case语句解释一下吗? - Pramod
@Pramod:已经编辑了我的先前回答中的switch/case。 :) - Ben Williams

-1
LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout);

Button b1 = new Button(this);


b1.setText("Btn");
b1.setId(int i=2);
b1.setonClicklistenor(this);
lin .addView(b1);

onclick (View v){


int i=v.getId();

if (i==2){

///operation
}
}
}

1
我不明白这如何回答问题。OP的问题是如何处理按钮的点击事件。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接