使用数组和setOnClicklistener中的数据动态创建按钮

时间:2013-06-12 16:21:53

标签: android loops button onclicklistener

我试图将OnClickListener添加到它由数组中的值生成的按钮,但是我没有这样做,这里有任何建议吗?

long lprice = Long.parseLong(searchId.getText().toString());
List<String> buttonNameOne = dbc.getItemNameRbPrice(lprice);
List<String> buttonPriceOne = dbc.getPriceRbPrice(lprice);
List<String> buttonDateOne = dbc.getCurrentDateRbPrice(lprice);

for(int i = 0 ; i < buttonNameOne.size() ;  i ++)
{
  Button btn = new Button(this);
  btn.setId(2000+i);
  btn.setText(buttonNameOne.get(i) + i);
  linearButton.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
  Log.v("Value of element "+i, buttonNameOne.get(i));
  Log.v("Value of element "+i, buttonPriceOne.get(i));
  Log.v("Value of element "+i, buttonDateOne.get(i));
}

1 个答案:

答案 0 :(得分:1)

您要做的是添加btn.setOnClickListener

for(int i = 0; i < buttonnameOne.size(); i++)
{
    Button btn = new Button(this);
    btn.setId(2000+i);
    btn.setText(buttonNameOne.get(i) + i));
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(view v) {
            // TODO Whatever you want onclick to do
        }
    });
    //Log stuff
    linearButton.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}