XML based approach, GUI, Layouts
XML based approach, GUI, Layouts
Statement Purpose:
In this lecture we will be learning how to use and extend the Android user interface library. In a number of ways it is very similar to the Java Swing library, and in perhaps just as many ways it is different.
Activity Outcomes:
At the end of this lecture students will be expected to know
- What Views, View Groups, Layouts, and Widgets are and how they relate to each
- How to declare layouts dynamically at
- How to reference resources in code and from other resource layout
- How to use Events and Event Listeners.
Instructor Note:
ANDROID APPLICATIONS BASICS
A single screen of UI that appears in your app
–the fundamental units of GUI in an Android app
–view: items that appear onscreen in an activity
–widget: GUI control such as a button or text field
–layout: invisible container that manages positions/sizes of widgets
- event: action that occurs when user interacts with widgets –e.g. clicks, typing
Designing a user interface/ Layout:
- Open XML file for your layout (e.g. activity_main.xml)
- Drag widgets from left Palette to the preview image
- Set their properties in lower-right Properties panel
Android-widgets/views:
Views are also referred to as widgets.
Typical examples include standard items such as the Button, CheckBox, ProgressBarand TextViewclasses.
Views have an integer id associated with them. These ids are assigned in the layout XML files.
Define a Button in the layout file and assign it a unique ID.
<Button android:id=”@+id/my_button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”@string/my_button_text”/>
Layout
layouts are described in XML and mirrored in Java code
–Android provides several pre-existing layout managers; you can define your own custom layouts if needed
–layout scan be nested to achieve combinations of features
Layout -Relative Layout
each widget’spositionandsizearerelativetoother views
–relativeto”parent” (the activity itself)
–relativetoother widgets/views
–x-positionsofreference:left, right, center
–y-positionsofreference:top,bottom, center
Relative anchor points
propertiesfor x/y relative to another widget:
layout_below,above,toLeftOf,toRightOf
set these to the Dofanother widget intheformat”@id/theID”
properties for x/y relative to layout container(the activity):
–layout_align ParentTop,Bottom,Left,Right
set these flags to a boolean value of “true” toenablethem
–layout_centerHorizontal,Vertical,InParent
set these flags to “true”to center the control within its parent in a dimension
Each widget has an associated Java object you can access they are subclasses of parent class View
<RelativeLayout…>
<Button…android:id=”@+id/b1″android:text=”B1″ android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true”/>
<Button…android:id=”@+id/b2″android:text=”B2″ android:layout_alignParentLeft=”true” android:layout_below=”@+id/b1″ />
<Button…android:id=”@+id/b3″android:text=”B3″ android:layout_centerHorizontal=”true” android:layout_below=”@+id/b2″ />
<Button…android:id=”@+id/b4″android:text=”B4″ android:layout_alignParentRight=”true” android:layout_below=”@+id/b2″ />
<TextView… android:id=”@+id/tv1″ android:text=”I’ma TextView!” android:layout_centerInParent=”true” />
<Button…android:id=”@+id/b5″android:text=”B5″ android:padding=”50dp” android:layout_centerHorizontal=”true” android:layout_alignParentBottom=”true” android:layout_marginBottom=”50dp”/>
</RelativeLayout>
Accessing View Objects in Java
Each widget has an associated Java object you can access they are subclasses of parent class View
–examples: Button, TextView, EditText, …
View objects have many get and set methods that correspond to the properties in the Design view:
–background, ID, margin, padding, text, textSize, visibility, …
–example: for a Button’s text property, there will be methods:
public String getText()
public void setText(String text)
From the on Create method of an Activity, the button’s object is created by following code:
Button myButton= (Button) findViewById(R.id.my_button);
Find-View-by-ID
This function is used to retrieve the widgets in the UI that you need to interact with programmatically.
- findViewById(intid) is a method of the View.
- This method will take a resource Id usually in the form of R.id.mViewand will return to you a View object that is a reference to that View.
- The returned object needs to be type casted to the correct type of View before you can start interacting with
TextViewanswerLabel= (TextView) findViewById(R.id.textView1);
Button getAnswerButton= (Button) findViewById(R.id.button1);
Input Events and Event Handling
Events are a useful way to collect data about user’s interaction with interactive components of applications like button press, screen touch etc. The android framework maintains an event queue as first-in, first-out (FIFO) basis. We can capture these events in our program and take appropriate action as per requirements.
Events are actions performed by users. It can be in any form. These events are the inputs to the applications. When application interacts with user it receives input in the form events. For example an event may be a button click, key press etc.
- Event Listeners −An event listener is an interface in the View class that contains a singlecallback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
- Event Listeners Registration −Event Registration is the process by which an Event Handler getsregistered with an Event Listener so that the handler is called when the Event Listener fires the
- Event Handlers −When an event happens and we have registered and event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the
Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register our event listener for any event, but we are going to discuss only 3 ways, out of which we can use based on the requirement or scenario.
- Using an Anonymous Inner Class
- Activity class implements the Listener
- Using Layout file xml to specify event handler directly.
The event handling approach is to capture the events and take appropriate response based on the event type. Event handling is accomplished with the help of event listeners and event handlers.
Event listeners listen to events and event handlers execute the appropriate code as response to the events. When a control is created it must be registered with event listener in order to, notified by
the listeners. When an event is triggered by users, the listeners are notified, and the listeners inform the event handlers that there is an event triggered. Then the event handler is executed, inside the event handler the code is written which is specifying what should happen for the event which was triggered.
‘OnClick’ Event
- Create ‘OnClick’ Event on Button Widget in Android Studio
OnClickListener
Interface definition for a callback to be invoked when a view is clicked.
onClick(View v):
Called when a view has been clicked.
setOnClickListener():
Register a callback to be invoked when this view is clicked.
OnClickListenerfor Button
public class MainActivityextends ActionBarActivityimplements OnClickListener{
Button myButton1 = null;
TextViewmyTextView= null;
@Override
protected void onCreate(Bundle savedInstanceState) {
myTextView= (TextView) findViewById(R.id.textView1);
myButton1 = (Button) findViewById(R.id.button1);
myButton1.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if(v.getId() == myButton1.getId()){
myTextView.setText(“Button 1 Clicked”);
}
}
ImageButton
Aclickablewidget withanimagelabel
tosetupanimageresource:
–putimage fileinprojectfolderapp/src/main/res/drawable
–use@drawable/footorefertofoo.png
usesimplefilenameswithonlyletters and numbers
EditText
Aneditabletext input box
Radio Button
A toggle able on/off switch; part of a group need to be nested inside a Radio Group tag in XML so that only one can be selected at a time
RadioGroup
<LinearLayout…
android:orientation=”vertical” android:gravity=”center|top”>
<RadioGroup… android:orientation=”horizontal”>
<RadioButton …android:id=”@+id/lions” android:text=”Lions”/>
<RadioButton …android:id=”@+id/tigers” android:text=”Tigers” android:checked=”true”/>
<RadioButton …android:id=”@+id/bears” android:text=”Bears,ohmy!”/>
</RadioGroup>
</LinearLayout>
On Click Listener for Radio Button
public class MainActivityextends ActionBarActivityimplements OnClickListener
{
RadioButtonmyRadioBtn1 = null;
RadioButtonmyRadioBtn2 = null;
TextViewmyTextView= null; @Overrid
protected void onCreate(Bundle savedInstanceState) {
. . . .
myTextView= (TextView) findViewById(R.id.textView1);
myRadioBtn1 = (RadioButton)findViewById(R.id.radioButton1);
myRadioBtn2 = (RadioButton)findViewById(R.id.radioButton2);
myRadioBtn1.setOnClickListener(this);
myRadioBtn2.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if(v.getId() == myRadioBtn1.getId())
{
myTextView.setText(“Radio Button 1 Clicked”);
}
else if(v.getId() == myRadioBtn2.getId())
{
myTextView.setText(“Radio Button 2 Clicked”); }
}
Spinner
A drop-down menu of select able choices. also need to handle events in Java code
–must get the Spinner object using find View By Id
–then call its set On Item Selected Listener method
String resources
Declare constant strings and arrays in res/values/strings.xml:
<resources>
<string name=”name”>value</string>
<string name=”name”>value</string>
<string-arrayname=”arrayname”>
<item>value</item>
<item>value</item>
<!–must escape’as\’ invalues–>
<item>value</item>
…
<item>value</item>
</string-array>
</resources>
Spinner example
Like combo-box in java swing (a dropdown will be displayed having the <items>.)
<LinearLayout …>
<Spinner… android:id=”@+id/tmnt” android:entries=”@array/turtles”/>
<TextView … android:id=”@+id/result” />
</LinearLayout>
inres/values/strings.xml:
<resources>
<string-array name=”turtles”>
<item>Leonardo</item>
<item>Michelangelo</item>
<item>Donatello</item>
<item>Raphael</item>
</string-array>
</resources>
Scroll View
A container withscrollbars around another widgetor container
<LinearLayout…>
…
<ScrollView android:layout_width=”wrap_content” android:layout_height=”wrap_content”>
<TextView …android:id=”@+id/turtle_info”/>
</ScrollView>
</LinearLayout>
Introduction
In this lab we will be learning how to use and extend the Android user interface library. In a number of ways it is very similar to the Java Swing library, and in perhaps just as many ways it is different. While being familiar with Swing may help in some situations, it is not necessary. It is important to note that this lab is meant to be done in order, from start to finish. Each activity builds on the previous one, so skipping over earlier activities in the lab may cause you to miss an important lesson that you should be using in later activities.
Activities:
ACTIVITY: Number game
- New let’s build that “Bigger Number” game! :
–user is shown two numbers
–must choose which one is bigger by clicking on the appropriate button
–game pops up brief “correct” / “incorrect” message after each guess
–get points for each correct answer (lose points for incorrect answers)
Displaying Toasts
Toast.makeText(this, “message”, duration).show();
–where duration is Toast.LENGTH_SHORTor LENGTH_LONG
- A “Toast” is a pop-up message that appears for a short
- Useful for displaying short updates in response to
Home Activities:
- Make an app that contains two Buttons (with labels “Push Me” and “Click Me”) and a TextView (with text “This is a Test”). Use the XML-based approach, and you can hardcode the label of the buttons and the text of the TextView inside main.xml (i.e., you do not need to use strings.xml at all yet). Use the android:text attribute in both cases, but it is easiest to use the visual editor first, then edit main.xml later. Nothing needs to happen when you press the
- Test your app on the
- If you have an Android phone or tablet, test your app on
- Update your app so that the Button labels and TextView text are taken from xml.
- Give your buttons some Here are some options for the button behaviors:
- Make them pop up Toasts (copy the code from one of the SayHello apps from the lecture, which is in your Eclipse projects)
- Have them change the foreground color of the Button that was clicked. Choose at random among RED, Color.BLUE, Color.YELLOW, etc. To change the color of the Button, call setTextColor on the Button that is passed to the event handler. However, note that although Button has a setTextColor method, View (the parent class of Button) does not. So, you have to cast the View to Button before calling setTextColor.
- Have them change the text of the Button to “I was clicked n times”. Use two instance variables for the counts. Use either the pure-XML way or the hybrid way of assigning the event handler. Test on the emulator and, if you have one, a real phone or
- Make a new app that is similar to the old one, but this time, when you press a button, it should change the color of the TextView instead of the color of the button that was pressed. You can assign the event handler either in XML or in Java, but you‟ll need to at least partially use the hybrid approach because you need an explicit Java reference to the TextView that was defined in the XML