0

I have made some buttons and stored them into an ArrayList. I need to add these buttons to my main activity layout.

I have tried to create a linearlayout and make that my main layout, however the buttons do not show.

   public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 // createButtons();setContentView(new CircleView(this));



}

public void createButtons() {


    ArrayList<Button> buttons = new ArrayList<>();

    int n = 0; // the number of buttons circumferencing the semicircle
    for(int i = 0; i < 6; i ++) {
        n = 7;
        Button button = new Button(this);
        double Xval = 500* Math.cos(i * Math.PI / n);
        double Yval = 500* Math.sin(i * Math.PI / n);
        button.setX((float)(Xval));
        button.setY((float)(Yval));

        buttons.add(button);

    }



}
}

I expect to have my buttons appear in my main activity layout.

1 Answers1

0

I Found some solutions for your case, but not the right solution, you must change it to your own implementation.

One way to do this, is create a layout and get the layout in code by id and in that you insert your buttons. This is one way to do this:

Button myButton = new Button(this);
myButton.setText("Push Me");

LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);

Inserting mutiple buttons with an event, even if I do prefer to implement OnClickListener on the class:

for (int i = 1; i <= 20; i++) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    Button btn = new Button(this);
    btn.setId(i);
    final int id_ = btn.getId();
    btn.setText("button " + id_);
    btn.setBackgroundColor(Color.rgb(70, 80, 90));
    linear.addView(btn, params);
    btn1 = ((Button) findViewById(id_));
    btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(view.getContext(),
                    "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

You can find many samples of android native in the link Android Samples

Source

Sham Fiorin
  • 403
  • 4
  • 16