Android Programming In Kotlin: Programming the UI |
Written by Mike James | ||||
Monday, 26 November 2018 | ||||
Page 2 of 3
To make this button a tiny bit more interesting we can customize it by setting properties. For example: val b = Button(this) b.text="Hello Button" setContentView(b) If you run this you will see a button that fills the screen with the caption "Hello Button". Don't bother setting any layout properties in code because at the moment there is no layout in force so they will be ignored. How to activate a layout is our next topic. The ViewGroupIf an Activity can only show a single View object, how can we ever create a complex UI with multiple buttons, textViews and other components? The answer, and you probably already guessed it, is that there are Layout, or ViewGroup, objects which can be used to host other View objects. You already know about using Layouts in the Layout Editor or in an XML file, but they, like all UI elements, correspond to particular classes that do the actual work. A ViewGroup can display multiple View objects. So in nearly all cases the View object that is associated with an Activity is a Layout View. When the Activity asks the Layout View to render itself, by calling its onDraw method, the Layout calls the onDraw method of each of the View objects it contains and puts them together to make a single result. Of course, it also performs a layout operation positioning and sizing the View objects it contains. So a Layout does two things:
To see this in action try: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val linLayout= LinearLayout(this) val b = Button(this) b.text="Hello Button" linLayout.addView(b) setContentView(linLayout) } If you run this program you will see a button at the very top left of the screen. The first instruction creates a LinearLayout object. This is a subclass of View that can contain other View objects and it organizes them in a left to right or top to bottom way depending on the setting of its orientation property. Next we create a button object and then use the standard addView method of the LinearLayout to add it to the layout. All Layouts have an addView method, which can be used to add multiple View objects. You can add more buttons to see how the default LinearLayout works: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val linLayout= LinearLayout(this) val b1 = Button(this) b1.text="Hello Button 1" linLayout.addView(b1) val b2 = Button(this) b2.text="Hello Button 2" linLayout.addView(b2) val b3 = Button(this) b3.text ="Hello Button 3" linLayout.addView(b3) setContentView(linLayout) } <ASIN:1871962544> <ASIN:1871962552> |
||||
Last Updated ( Monday, 26 November 2018 ) |