-3

I want to add some ui elements to my android app, a Button for example! But I can't find a complete tutorial! I found this code after a lot of searches:

LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);

My first problem is first line! Can you explain it for me please? What is R.id.layout? I know R is an object for resources but I don't know what is layout! Second problem is line 3, What is LayoutParams?

Thank you all!

miljon
  • 2,611
  • 1
  • 16
  • 19
P.Karimyan
  • 43
  • 1
  • 10

3 Answers3

1
 LinearLayout ll = (LinearLayout)findViewById(R.id.layout);// you are getting a refrence to your layout
 Button btn = new Button(this); // creating a new object of button type
 btn.setText("Manual Add"); //setting the button text
 btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
 LayoutParams.WRAP_CONTENT)); //setting the width and height of the element
 ll.addView(btn);//adding the button to your layout

R.id.layout is the name of your activity layout

radtelbi
  • 635
  • 1
  • 6
  • 18
1

You can create views using default constructors for example

Button button = new Button(context);

After that you should determine to which type of parent view you are going to attach it, and create corresponding layot params. Every parent view LayoutParams type has uniqe customize methods, for example rules of RelativeLayout.LayoutParams.

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height)
//customize params here
button.setLayoutParams(params)

Attach view to your parent view

frameLayout.addView(button)

That is it.

Ufkoku
  • 2,384
  • 20
  • 44
0

It is the parent view which you are going to add your views. In your example it is a LinearLayout called layout.

Distwo
  • 11,569
  • 8
  • 42
  • 65