简体   繁体   中英

Adding dynamically several Button to several LinearLayout

I would like to add buttons to different LinearLayout dynamically (with Java) but before that I have to add LinearLayout to the main View which is also a LinearLayout by the way.

Here is my code:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    globalLinear = (LinearLayout) findViewById(R.id.viewButtons);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);

    for(int i = 1; i <= nbButton; i++) {
        if(i % 3 == 0) {
             row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
        }
        Button b = new Button(this);
            int number = generator.nextInt(complexity);

            b.setText(number+"");
            row.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT,
                                           LayoutParams.WRAP_CONTENT) );    
    }
}

R.id.viewButtons is the main (vertical) LinearLayout inside. R.layout.row_buttons is a horizontal LinearLayout .

As you can see above, I am trying to get 3 buttons per LinearLayout with (i % 3 == 0) But it seems new LinearLayout are never created.

Thank you for your help :)

您可能需要定义线性布局,在循环内创建它的新实例,以便在执行循环之前就可以创建它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM