android - 如何创建动态组按钮

时间:2013-09-02 15:56:06

标签: java android android-layout button margin

我有运行时按钮的名称列表。我该如何创建按钮?

    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;
    }

我尝试了这个,但没有任何作用,按钮隐藏在一排,而不是下面。

在此之后,我想动态地对按钮点击事件和开始不同的活动作出反应。

1 个答案:

答案 0 :(得分: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++; 
}

以下是您可以使用的示例代码:useful link