I have coded a layout (i.e LinearLayout with toolbar, code below just for an example) and I want to load it in a new window, like I start new intent, what is the correct way of doing this?
protected Void startNewLayout() {
LinearLayout myLayout= new LinearLayout(context);
Toolbar toolbar = new Toolbar(context);
toolbar.setTitle("Page#1");
myLayout.addView(toolbar);
TextView text = new TextView(context);
text.setText("Hello World!");
myLayout.addView(text);
//open myLayout
}
First you have to create the layout, then you have to create LayoutParams. The constructor takes two parameters: width and height. We set both as MATCH_PARENT. After this, setContentView method is invoked. LinearLayout and LayoutParams are passed to it as parameters. This means that LinearLayout with layout-attributes from LayoutParams will be the root element.
You have to again create LayoutParams object with width = wrap_content and height = wrap_content attributes. Now if you assign this object to one of the Views, this View will have width and height defined by its content.
After this we create a Toolbar, update its text, set it previously created LayoutParams object and add it to LinearLayout using addView(View child) method. The same thing will be happened with the TextView.
So, your Final code will be look like this!
protected Void startNewLayout() {
LinearLayout myLayout = new LinearLayout(context);
myLayout.setOrientation(LinearLayout.VERTICAL);
// creating LayoutParams
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// set LinearLayout as a root element of the screen
setContentView(myLayout, layoutParam);
LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Toolbar toolbar = new Toolbar(context);
toolbar.setTitle("Page#1");
toolbar.setLayoutParams(lpView);
myLayout.addView(toolbar);
TextView text = new TextView(context);
text.setText("Hello World!");
text.setLayoutParams(lpView);
myLayout.addView(text);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments