开发者

Dynamically adding Buttons in Android doesn't work after the first Button is added

I have a button that I have created in code, which has a listener for Click events. Every time that the button is clicked, it should generate another button and add it below the original button. However, no matter how many times I click the first button, it will only add a dynamic button once, and not add any more.

Here is my coding:

public class DynaminControlActivity extends Activity {
    private RelativeLayout container;
    private int mainIdCnt = 0;
    private int mainId = 100;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createMainButton();
    }

    public void createMainButton() {
        container = (RelativeLayout) findViewById(R.id.workLayout);
        Button b = new Button(this);
        b.setId(mainIdCnt + mainId);
        CharSequence text = "Main +";
        b.setText(text);
        container.addView(b);
        if (mainId > 0) {
            mainId++;
        }
        b.setOnClickListener((new View.OnClickListener() {
            public void onClick(View v) {
                createDynamicButton();
            }
        }));
    }

    public void createDynamicButton() {
        container = (RelativeLayout) 开发者_如何学GofindViewById(R.id.workLayout);
        Button b = new Button(this);
        CharSequence text = "Main +";
        b.setText(text);
        RelativeLayout.LayoutParams relLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relLayout.addRule(RelativeLayout.BELOW, mainIdCnt + mainId);
        container.addView(b, relLayout);
        if (mainId > 0) {
            mainId++;
        }
    }


A few things...

  1. If your main layout is a LinearLayout, you shouldn't need to add a rule to indicate that the button should appear underneath the existing button - it will automatically be added to the very bottom (vertical alignment) or very right (horizontal alignment) of the layout.

  2. All your buttons have the same text. Are you certain that you're clicking the first button each time? I note that only your first button has a listener on it, so if you're accidentally clicking one of the other buttons then nothing will happen.

  3. If you're intending to add multiple buttons, it will quickly expand to be larger than the screen size, so you should make sure that your main layout is within a ScrollView so that you can see all the buttons you add

  4. The call to setId() might be stuffing around with the internal workings of Android. Rather than setting an ID, you should let Android generate the ID automatically, and just retrieve that value if you need to reference it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜