Changes

Creating an Android 6 User Interface in Java Code

33 bytes removed, 20:01, 27 October 2016
m
Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">"
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_layout);
}
</pre>
}
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
When new instances of user interface objects are created in this way, the constructor methods must be passed the context within which the object is being created which, in this case, is the current activity. Since the above code resides within the activity class, the context is simply referenced by the standard Java this keyword:
Button myButton = new Button(this);
</pre>
<googlehtmlet>ADSDAQBOX_FLOWadsdaqbox_flow</googlehtmlet>
Once the above additions have been made, compile and run the application (either on a physical device or an emulator). Once launched, the visible result will be a button containing no text appearing in the top left hand corner of the RelativeLayout view as shown in Figure 17-1:
So far in this tutorial it has not been necessary to use view IDs. In order to demonstrate the use of IDs in Java code, the example will now be extended to add another view in the form of an EditText view that will be configured to be aligned 80 pixels above the existing button and centered horizontally. The following code modifications add the new view to the activity and then set IDs of myButtonId and myEditTextId on the Button and EditText views respectively. Layout parameters are then created for the EditText view so that it is aligned with the button (note the call to getId() on the button to get the view ID) and centered horizontally within the layout. Finally, the margins property of the EditText field is configured to set the bottom margin to 80 pixels before adding the new view to parent layout.
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
The view IDs first need to be declared as value resources. Right click on the app -> res -> values folder, select the New -> Values resource file menu option and name the new resource file id.xml. With the resource file created, edit it so that it reads as follows:
}
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
Compile and run the application one more time and note that the width of the EditText view has changed as illustrated in Figure 17-3:
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
 
<htmlet>ezoicbottom</htmlet>
<hr>
<table border="0" cellspacing="0" width="100%">