创建按钮列表并将其添加到布局

时间:2013-02-12 08:08:25

标签: android android-layout

我有两种方法:

public View addNewLinearLayout(Context context) {
    LinearLayout linearLayout = new LinearLayout(context);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    params.height = 120;
    linearLayout.setLayoutParams(params);
    linearLayout.setBackgroundColor(Color.RED);
    linearLayout.setGravity(Gravity.TOP);
    linearLayout.addView(buttonsGenerator(context));
    return linearLayout;
}
public View buttonsGenerator(Context context){
    ListView lst;
    lst = new ListView(context);

    Button button = new Button(context);

    return lst;
}

在addNewLinearLayout中,我添加了要查看的布局。在buttonsGenerator中,我想添加一些按钮来列出,并在addNewLinearLayout的布局中添加带有按钮的列表。如何创建按钮列表并使用方法buttonsGenerator将其添加到线性?

1 个答案:

答案 0 :(得分:1)

例如:

public View addNewLinearLayout(Context context) {
    LinearLayout linearLayout = new LinearLayout(context);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    params.height = 120;
    linearLayout.setLayoutParams(params);
    linearLayout.setBackgroundColor(Color.RED);
    linearLayout.setGravity(Gravity.TOP);

    List<View> components = getButtons(context);
    for(View component : components) {
       linearLayout.addView(component);
    }

    return linearLayout;
}

public List<View> getButtons(context) {
    List<View> buttons = new ArrayList<View>();
    for(int i = 0; i < 10; i++) {
       buttons.add(createButton(context));
    }
    return buttons;
}

public View createButton(Context context){
    ListView lst;
    lst = new ListView(context);

    Button button = new Button(context);

    return lst;
}

但最好使用listview而不是这个。