0

im pretty new to Android Studio and I already did some research but didn't found a solution. I want to create an object (button) at runtime per Java. I already tried this:

In global:

Button btn;

In method:

Button btn = (Button) findViewById(R.id.btn);

But this isn't working. So can somebody show me, how I can create a button at runtime and also how to change the attributes.

Thank You

Pumpanickel
  • 91
  • 2
  • 10

1 Answers1

0

findViewById searches for layout elements by the id attribute. You don't have one on your button; you can't just use the variable name and expect it to work.

Button btn = new Button(this);

To add attributes:

btn.setText("My Button");

You will also need to add your button to the layout to get it to show up. In your layout XML, give your layout (LinearLayout, RelativeLayout, etc.) an ID. Then:

mLayout = findViewById(R.id.layoutMain);
mLayout.addView(btn);
Matt
  • 2,953
  • 3
  • 27
  • 46
  • LinearLayout ll = findViewById(R.id.linearLayout); ll.addView(btn, 2, 5); I tried it like this, but isn't working, what am I doing wrong? And already thank you fo your good help :) – Pumpanickel Dec 19 '17 at 00:00