0

I have list of names for buttons in runtime. How can I create buttons?

    int marginTop = 0;

    for(String s : locations){
        Button button = new Button(this);
        button.setText(s);
        //setContentView(button);

        //ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        //MarginLayoutParams src = new MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.WRAP_CONTENT);
        //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(src);
        //params.setMargins(0, marginTop, 0, 0);
        //this.addContentView(button, params);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(0, marginTop, 0, 0);

        button.setLayoutParams(params);
        this.addContentView(button, params);
        marginTop += 50;
    }

I tried this, but nothing works, buttons are hide in a row, not below.

And after this I want to dynamically react to buttons click event and starting diffrent activities.

4

1 回答 1

0
    for(String s : locations){
 Button button = new Button(this);
 button.setText(s);
 button.setId(ID);
 LinearLayout mylayout = (LinearLayout)findViewById(R.id.location_layout); mylayout.setOrientation(LinearLayout.VERTICAL);
 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.La‌​youtParams.WRAP_CONTENT);
 params.setMargins(0, marginTop, 0, 0);
 button.setLayoutParams(params);
 mylayout.addView(button);
 marginTop += 5;
 ID++; 
}

这是您可以使用的示例代码:有用的链接

于 2013-09-02T15:59:20.787 回答