3

Is there any way to combine xml-based layout and "manual" layout? F.ex.:

I use the "standard" xml layout like this:

 setContentView(R.layout.mainscreen);

And then I want to have some more dynamic contents, adding it like this:

 LinearLayout layout = new LinearLayout(this);
 setContentView(layout);
 layout.addView(new CreateItemButton(this, "Button", 1));

I realize of cours that I cannot create a new layout like in the line above, but I'd probably have to initialize the xml layout in some way. But - is it possible, or do I just have to go with a 100% manual layout if I want to dynamically add components? Or is there perhaps another, more elegant/correct way of doing it?

(What I want to do is create buttons based on entries fetched from a database. These will wary in number and text/contents, hence the attempt to add them dynamically instead of in the xml layout file.

2 Answers 2

6

You can add any element dynamically to your xml layout. You have to have a container in your xml layout where you are going to add your dynamic elements. Say empty LinearLayout with id="container". Also you can build everything dynamically and setContentView(yourView); Where is yourView is a root layout element with other child elements added.

EX:

Button myButton = new Button(this);
myButton.setLayoutParams(params);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
container.addView(myButton);

or

LinearLayout myLayout = new LinearLayout(this);  
...
container.addView(myLayout);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Maxim - that worked. Not sure why I didn't get it to work before, but now I'm able to both add "static" contents in the xml file AND add dynamic contents directly in my code.
1

I hope it will helpful to you.

Try this Code...

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);   

       RelativeLayout rl= (RelativeLayout) findViewById(R.id.rl);
       Button b2=new Button(this);
       b2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
       b2.setText("Dynamic");
       b2.setTextSize(30);
       b2.setTextColor(b1.getTextColors());
       rl.addView(b2);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.