Android Add button and respond

Source: Internet
Author: User

1. First create a new two button tag in the Activity_main.xml file.

  

1 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 android:orientation= "vertical"6 Android:paddingbottom= "@dimen/activity_vertical_margin"7 Android:paddingleft= "@dimen/activity_horizontal_margin"8 Android:paddingright= "@dimen/activity_horizontal_margin"9 Android:paddingtop= "@dimen/activity_vertical_margin"Ten Tools:context= "Com.fate.testproject.MainActivity" > One  A     <TextView -         Android:layout_width= "Match_parent" - Android:layout_height= "Wrap_content" the Android:text= "@string/total"  - android:textsize= "45SP" - android:layout_gravity= "Center"  - android:gravity= "Center" + Android:id= "@+id/tvtotal" -         /> +      A     <Button at         Android:layout_width= "250SP" - Android:layout_height= "Wrap_content" - Android:text= "@string/addone" - android:layout_gravity= "Center" - android:textsize= "20SP" - Android:id= "@+id/baddone" in         /> -     <Button to         Android:layout_width= "250SP" + Android:layout_height= "Wrap_content" - Android:text= "@string/subone" the android:layout_gravity= "Center" * android:textsize= "20SP" $ Android:id= "@+id/bsubone"Panax Notoginseng         /> -  the  + </LinearLayout>

There are a few problems here.

1) Layout problem: I am now using the Android environment is up to date, the new project under the Activity_main.xml file self-layout is not linearlayout linear layout. There was something wrong with the contents of the book and the online video tutorials. Later, after changing to linearlayout linear layout, it was found that several controls were squeezed into a horizontal position, and the controls were even extruded out of view. The original linear layout defaults to horizontal, not what we think of as vertical. Add a sentence here

android:orientation= "Vertical", all spaces are vertically arranged in turn.
2) Hard coding problem: I used a numeric value when defining the width and height of the control (height). The average person now knows that if you use pixel DX as your unit to define the width and height of the control, a yellow warning of warning will appear. But I also had the warning when I used DP as the unit, and finally the SP was used at the prompt. Also, the warning warning occurs when you define Android:text, without referencing the elements under string and entering content directly. This hard-coded warning warning generally does not cause the whole program to go wrong, but good habits and programming ideas reduce the probability of errors.
3) I set the ID when there is a small problem, write the wrong, will android:id= "@+id/bsubone" written android:id= "@id/bsubone" less A + number, resulting in the program can not run completely, Red alert appears. Please be careful.

2. Second, add elements to the String.xml file under Resources
1 <?XML version= "1.0" encoding= "Utf-8"?>2 <Resources>3 4     <stringname= "App_name">TestProject</string>5     <stringname= "Hello_world">Hello world!</string>6     <stringname= "Action_settings">Settings</string>7     <stringname= "Total">Total is: 0</string>8     <stringname= "Subone">Value minus One</string>9     <stringname= "AddOne">Value plus One</string>Ten  One </Resources>

Add some of the button information here, more convenient to modify and manage. If necessary, refer directly to it.

3. Add a response function in the Mainactivity function

1  PackageCom.fate.testproject;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 ImportAndroid.view.Menu;6 ImportAndroid.view.MenuItem;7 ImportAndroid.view.View;8 ImportAndroid.widget.Button;9 ImportAndroid.widget.TextView;Ten  One  A  Public classMainactivityextendsActivity { -  -     intCounter//Create an int variable counter theButton Maddone, Msubone;//Create two button variables, plus one button and minus one button -TextView Mtotal;//Create a variable of type TextView mtotal -      - @Override +     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); A          at          -         //Initialize the value of a variable -Counter = 0; -          -         //associating two button and TextView variables -Maddone =(Button) Findviewbyid (r.id.baddone); inMsubone =(Button) Findviewbyid (r.id.bsubone); -Mtotal =(TextView) Findviewbyid (r.id.tvtotal); to          +         //Add a button stand-alone response function -Maddone.setonclicklistener (NewView.onclicklistener () { the              * @Override $              Public voidOnClick (View v) {Panax Notoginseng                 //TODO auto-generated Method Stub -counter++; theMtotal.settext ("Total:" +counter); +             } A         }); the          +Msubone.setonclicklistener (NewView.onclicklistener () { -              $ @Override $              Public voidOnClick (View v) { -                 //TODO auto-generated Method Stub -counter--; theMtotal.settext ("Total:" +counter); -             }Wuyi         }); the     } -  Wu  - @Override About      Public BooleanOncreateoptionsmenu (Menu menu) { $         //inflate the menu; This adds items to the action bar if it is present. - getmenuinflater (). Inflate (R.menu.main, menu); -         return true; -     } A  + @Override the      Public Booleanonoptionsitemselected (MenuItem item) { -         //Handle Action Bar item clicks here. The Action Bar would $         //automatically handle clicks on the Home/up button, so long the         //As you specify a the parent activity in Androidmanifest.xml. the         intID =Item.getitemid (); the         if(id = =r.id.action_settings) { the             return true; -         } in         return Super. onoptionsitemselected (item); the     } the}

Simply add a button that only needs to modify the files under these three projects.

Here I am in order to develop their own habits, let me write out the code is more readable. This is the case when I define individual variables.

1) Follow the definition name to make sense, basically represent the content or meaning of the control, and use English as much as possible to represent its meaning. such as: Add one I will define into AddOne

2) The definition of a control's id,name, or other function-related associations, takes a slightly different definition. String name in string is usually preceded by a lowercase letter, followed by the first uppercase of each word, and the set ID is preceded by an abbreviated letter of its label (for example, the button label is preceded by the string name, and the first letter is capitalized, The letter TV is added under the TextView tag, and the first letter of the TV is capitalized); When you use the associated variable in other functions, such as the mainactivity function, the letter m is preceded by the string name and the first letter of the M is capitalized.

Example: Create a plus button then string name is Addone,id, which is Baddone, the function variable associated with the main function is Maddone.

3) Note the sections, branches, and make the entire code look layered. Easy to read, easy to modify. Also can let themselves write code when the mood is better, because the code can not be a one-time write well finished, always go back to modify the view, if there is no good level of feeling, it is difficult to look at their own writing code when there is a good mood, which not only affect work and learning, but also to combat our enthusiasm for development.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.