Practical Application of components
Now that the button has a resource ID, you can get them directly in the quizactivity. First, add two member variables in the Quizactivity.java file, as follows:
Public class extends Activity { private Button Mtruebutton; Private Button Mfalsebutton; @Override protectedvoid onCreate (Bundle savedinstancestate) { Super . OnCreate (savedinstancestate); Setcontentview (R.layout.activity_quiz); } ...}
Code Listing 1-8: Adding a member variable (QUIZACTIVITY.JAVA)
After saving the file, you can see two error prompts. Note the M prefix for the new two member (instance) variable names . This prefix is the naming convention followed by Android programming, and this book will always follow that convention.
Now, move your mouse to the error prompt at the left of the code to see two identical errors: Button cannot be resolved to a type.
This error message tells us that we need to import the Android.widget.Button class package in the Quizactivity.java file. You can manually enter the following code at the head of the file:
Import Android.widget.Button
Or a convenient way to introduce the shrimp is automatically imported.
Class Package organization Import
Organizing the import with a class package is to let eclipse determine which Java or Android SDK class packages should be imported based on the code . If the previously imported class packages are no longer needed, eclipse will automatically delete them as well.
Use the following key combination commands to organize the class package import:
Command+shift+o (Mac System);
Ctrl+shift+o (Windows and Linux systems).
After the class pack import is complete, the error prompt just now should be gone. (If the error message persists, check the Java code and the XML file to see if there is an input or spelling error.) )
Next, let's encode the use of a button component, which requires the following two steps:
Reference the generated View object;
Sets the listener for the object in response to user actions.
Application components
In activity, the generated components can be referenced by the following activity methods:
Public int ID)
The method takes the resource ID of the component as a parameter and returns a View object.
In the Quizactivity.java file, once the generated object is obtained using the resource ID of the button, the corresponding member variable is assigned, as shown in Listing 1-9. Note that before assigning a value, the returned view must be transformed (cast) to a button.
Public classQuizactivityextendsActivity {PrivateButton Mtruebutton; PrivateButton Mfalsebutton; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_quiz); Mtruebutton = (Button) Findviewbyid (R.id.true_button); Mfalsebutton = (Button) Findviewbyid (R.id.false_button); }
Code Listing 1-9: Referencing a component (Quizactivity.java)
Setting up listeners
Android apps are typical event-driven types . Unlike a command line or a script, when the event-driven app starts, it begins to wait for the behavior event to occur, such as when a user clicks a button. (events can also be triggered by the operating system or other apps, but the events triggered by the user are more obvious.) )
The app waits for a specific event to occur, or it can say that the app is "listening" for a specific event. An object created to respond to an event is called a listener (listener). A listener is an object that implements a specific listener interface to listen for the occurrence of a class of events.
The Android SDK has developed a number of listener interfaces for various events built in. The current app needs to listen for the user's button "Click" Event , so the listener needs to implement the View.onclicklistener interface.
The true button is processed first, as shown in the following code:
@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_quiz); Mtruebutton=(Button) Findviewbyid (R.id.true_button); Mtruebutton.setonclicklistener ( New View.onclicklistener () {@Override public void oncli CK (View v) { // Does Nothing yet, but soon! } } ); Mfalsebutton=(Button) Findviewbyid (R.id.false_button); }
Code Listing 1-10: Set Listener for True button (Quizactivity.java)
(If you encounter an error with the view cannot be resolved to a type, use the command+shift+o of your Mac or the Ctrl+shift+o shortcut key for Windows to import the View class.) )
In code listing 1-10, we set up a listener. When the button Mtruebutton is clicked, the listener will notify us immediately. the Setonclicklistener (Onclicklistener) method is called with the listener as a parameter . In special cases, the method is invoked as a parameter to an object that implements the Onclicklistener interface .
? using anonymous inner classes
Setonclicklistener (Onclicklistener) method The listener parameter passed in is an anonymous inner class (Anon-ymous inner Class) implementation, and the syntax looks slightly more complicated, but Just remember that the entire implementation code inside the outermost parentheses is the one that is passed into the Setonclicklistener (Onclicklistener) method as a global parameter.
Can The passed-in parameter is the implementation code for the newly created anonymous inner class.
New View.onclicklistener () { @Override publicvoid OnClick (View v) { // Does Nothing yet, but soon! } } );
The listener is implemented as an anonymous inner class. the benefits of doing so are two . First, in a large number of code blocks, the implementation of the listener method is at a glance; second, the use of anonymous internal classes only appears in one place, so you can reduce the use of some named classes .
The anonymous inner class implements the Onclicklistener interface, so it must also implement the unique onclick (View) method for that interface . The code for the OnClick (View) method is temporarily an empty structure. Implementing the listener interface requires the implementation of the OnClick (View) method, but how it is implemented is determined by the consumer, so even if the implementation method is empty, the compiler can
Compiled by.
We set a similar time listener for the false button.
Mfalsebutton = (Button) Findviewbyid (R.id.false_button); New View.onclicklistener () { @Override publicvoid OnClick (View v) { // Does Nothing yet, but soon! } } );
Code Listing 1-11: Setting the listener for the false button (Quizactivity.java)
Create a prompt message
The next thing to do is to click the two buttons, respectively, to pop up the prompt message we call toast. An android toast is a short pop-up message that notifies the user, but does not require the user to enter or make any action. Here, all we have to do is use a toast to tell the user whether the answer is correct or not.
First, go back to the Strings.xml file, as shown in Listing 1-12, to add a string resource for the toast message display.
<?xml Version = "1.0" encoding = "Utf-8"?><resources> <string name = "App_name" > Geoquiz </stri ng> <string name = "Question_text" > Constantinople is the largest city in Turkey. </string> <st Ring name = "True_button" > True </string> <string name = "False_button" > False </string>
<string name = "Correct_toast" > correct! </string>
<string name = "Incorrect_toast" > incorrect! </string> <string Name = "Action_settings" > Settings </string> <!--Each person's version is different, the star month here differs from the book. The book is: name = "Menu_settings"--></resources>
Code Listing 1-12: increasing the toast string (Strings.xml)
You can create a toast by calling the following methods from the Toast class:
Public Static int int duration)
The context parameter of the method is usually an instance of activity (the activity itself is a subclass of the context). The second parameter is the resource ID of the toast-to-display string message. The toast class must take advantage of the context to find and use the resource ID of the string. The third parameter, typically one of two toast constants, is used to specify toast messages
The duration of the display.
After you create a toast, you can make the toast message appear on the screen by calling the Toast.show () method.
In the quizactivity code, the listener for the two buttons is called Maketext (...) respectively. method, as shown in code listing 1-13. in the Add Maketext (...) , you can make code entry work easier by leveraging Eclipse's code auto-completion functionality .
Mtruebutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (quizactivity. This, R.string.incorrect_toast, Toast.length_short). Show (); }} ); Mfalsebutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (quizactivity. This, R.string.correct_toast, Toast.length_short). Show (); }} );
Code Listing 1-13: Creating a hint message (Quizactivity.java)
Using Code Auto-completion
The automatic completion of the code can save a lot of development time, and the sooner you learn the benefits the more. Refer to Code Listing 1-13 and enter the code in turn. When you enter the point number after the Toast class, Eclipse pops up a window that shows the constants and methods of the suggested Toast class.
To make it easier to choose the recommended method you want, press the TAB key to focus on the AutoComplete pop-up window. (If you want to ignore Eclipse's Code AutoComplete feature, do not press the TAB key or use your mouse to click the Pop-up window, just continue to enter the code until you finish.) )
In the list suggestion checklist, select the Maketext (Context, int, int) method, and the code auto-completion feature automatically adds the completion method call, including the parameter's placeholder value.
The first placeholder symbol is highlighted by default, directly entering the actual parameter value Quizactivity.this. Then press the TAB key to go to the next placeholder, enter the actual parameter value, and so on, until you complete the input of all parameters in the reference code listing 1-13.
In Maketext (...) , the Quizactivity instance is passed in as the parameter value of the context. Note that the parameter that should be entered here is quizactivit.this, and do not take this as a direct input to this parameter . because of the use of anonymous classes, this here refers to the listener View.onclicklistener.
(original) "Android Programming Authority Guide" learning note 01--Android app first experience--006