当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Create buttons dynamically in while loop

问题描述:

I want to create some buttons in java for an android app dynamically. I get names with regex and theese names should be the button text. For example there are 5 names so I need 5 buttons. I tried it like this:

for(int i2 = 0; i2<chars.length; i2++) {

Pattern p = Pattern.compile("name~(.*?)@");

Matcher m = p.matcher(chars[i2]);

while (m.find()) {

createButton(m.group().toString().replace("name~", "").replace("@", ""), i2);

}

}

public void createButton(String buttontext, int number2) {

Button btn = new Button(this);

btn.setText(buttontext);

btn.setX((number2+1)*25);

btn.setY((number2+1)*30);

LinearLayout ll = (LinearLayout)findViewById(R.id.cmdExample);

LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

ll.addView(btn, lp);

btn.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

Intent myIntent = new Intent(getApplicationContext(), Example.class);

startActivityForResult(myIntent, 0);

}

});

}

But then the app totally crashes. Can anyone help?

分享给朋友:
您可能感兴趣的文章:
随机阅读: