An accessible aboriginal activity for Android development noobs: Math Game

For those absorbed in acquirements Android development, this column will accommodate an ideal aboriginal activity to advice you put your ability into practice.

You can apprehend about Android development until you’re dejected in the face, but eventually you absolutely accept to body article if you appetite to get a accurate butt on how it all works.

In fact, I anticipate this is a book area the actual best way to apprentice is by doing. Until you absolutely dive into Android Studio and alpha aggravating to body a alive app, you won’t accept any ambience for the advice you are absorbing. You won’t see what it is for, or how it all works together.

This column will adviser you through a actual simple aboriginal Android Studio project. This will appearance you all the pieces of the addle as they assignment together, and let you to absolutely analysis some of the approach you’ve best up so far. I’ll be operating beneath the acceptance that you accept done a little accomplishments account on Java and Android, but I’ll still go over aggregate as abundant as accessible to adviser you through the process. The action should be ideal for addition new to Android development.

We will be architecture a algebraic game. But that isn’t absolutely what’s important; you can aloof as calmly about-face architect this to be annihilation else!

If you haven’t got a archetype of Android Studio, go advanced and follow this column for instructions on how to get it.

Once installed, alpha a new project. Alarm it whatever you like, but accomplish abiding to accept “Empty Activity.” This agency that the app “template” will be abandoned and bare of buttons and airheaded which can contrarily get complicated for a newbie. Leave all added options as default.

Once that has loaded up, you’ll be presented with your aboriginal project. Android Studio has lots of windows, which can be appealing alarming aback you’re starting out. Don’t anguish about them. Instead, artlessly focus on the best important two: the window with the cipher on the appropriate and the one with the agenda on the left.

The window on the appropriate is area you ascribe and adapt your code. The window on the larboard is area you accept which book it is you appetite to edit. You can additionally accessible assorted files at already and afresh flick amid them appliance tabs forth the top of the capital window. Appropriate now, you should accept two files open: activity_main.xml and MainActivity.java. The closing will acceptable be alleged and you’ll be able to see the basal cipher it contains.

This cipher is what we alarm “boilerplate code” — the absence cipher Android Studio fills out on your behalf. This is advantageous cipher appropriate for the majority of projects, but you can avoid it for now.

These two files are accessible because they are the best important files in any new project. An action is any angle abandoned awning in an appliance — in some cases it will accommodate the absolute app. This consists of two files: one to ascertain what it looks like, alleged an XML file, and one to ascertain how it behaves, alleged a java file.

The XML book tells Android area to abode the buttons, the images, and any added important files. Meanwhile, the Java book defines how these buttons and images behave, like what happens aback you bang on a button.

You’ll acquisition MainActivity.java in: app > java > [package name of your app] > MainActivity.

Because the XML book defines a layout, which is graphical in nature, it is a “resource” file. This afresh goes in: app > res > blueprint > activity_main.xml. Book names can’t accept spaces and ability files can’t use high case, which is why the two words are abutting via an underscore.

Click on the tab at the top that says ‘activity_main.xml’ in adjustment to about-face to that file. Accomplish abiding you accept the Architecture tab alleged at the basal of the awning rather than the Argument tab (which shows the XML code).

This architecture appearance will acquiesce you to annoyance and bead elements assimilate the awning to set them out about you like. Best Android apps use “views,” which are all the elements you are apparently accustomed with from appliance apps on your own device, like buttons, images, and argument boxes. With the architecture view, we can set these up absolutely accurately and easily; aloof acquisition the aspect you appetite on the larboard (under Palette) and afresh annoyance and bead it assimilate the account of your app.

You already accept one “textView” in the average of the awning which says “HelloWorld.” We’re action to about-face that into our title. But we additionally appetite two added textViews underneath, to appearance the two numbers we appetite to present the user, as able-bodied as an “editText” which will be acclimated for them to ascribe their answer. Use the account in palette alleged “Number” and this will confine the ascribe to numbers online.

Lastly, add a button so they can abide their acknowledgment and a final textView to say if they got it right.

You will acceptable that these elements can be a little adamant and sometimes debris to go area you appetite them. That’s because we’re appliance a blazon of blueprint alleged “Constrain Layout,” which agency all angle are positioned about to one addition and the edges of the device. To move your angle around, you charge to grab assimilate the bend of one, annoyance it to a anchored point, and do the aforementioned for the added three sides. Already you’ve done that, you can afresh acclimatize its position amid those anchored points.

You should end up with article that looks a bit like this, but it’s up to you how you’d like to position your elements!

Select any of the angle and a window on the appropriate alleged “attributes” should acquaint you a bit about them.

Here you can change backdrop like the name of the appearance or the argument it displays. If you accept “Hello World!” you can change this to appearance the name of your app by alteration the advantage that says “text.” Let’s change that to “Maths Game!.” The s is optional, I’m British.

Likewise, change the argument on the Button so it says “Submit” and accomplish the others blank.

Now accept the aboriginal bare textView and change the advantage at the top of the Attributes that says “ID” to “Number1.” This “ID” won’t be apparent by the user, but rather it’s acclimated to analyze our angle from aural the Java code. If we appetite to address cipher to adapt the behavior of a view, we charge to acquaint Android which appearance we’re action to be changing! Alarm the abutting one “Number,” alarm the editText “Attempt,” alarm the button “Submit” and alarm the argument at the basal of the awning “Answer.”

Finally, bang on the button afresh and area it says “onClick,” address “onSubmitClick.” An “onClick” is a allotment of cipher accomplished whenever a appearance gets clicked. This is addition way for us to calmly accredit to our views.

Your app is now actual appealing but it doesn’t absolutely do abundant as yet. To antidote that, arch aback to the “MainActivity.java” book by allotment the tab forth the top.

With this folio open, you can now alpha abacus cipher cogent those buttons and textViews how to behave.

See Also: hack facebook

The aboriginal affair to do is change the two numbers so they appearance accidental text. To do that, we charge to locate them via our code.

Remember we said that “boilerplate” cipher was cipher Android Studio had abounding in for you. That includes the “onCreate” method, which is a area of cipher that runs as anon as an action is created. Methods are artlessly acceptable bundles of code, which are independent aural coiled brackets.

We can see in actuality this line:

This is what tells Java that activity_main.xml is area the blueprint is defined. It additionally agency we can now advertence our angle from that book by appliance the ID.

So, if we appetite to change the argument of our Number1 view, afresh we could do the following:

If you see a red underline, you’ll charge to “import a class.” This is basically cogent Android Studio you appetite to use added features, so aloof bang on the behind argument and afresh bang “Alt Enter” as instructed to bound admission that feature!

What happened actuality is we accept created a variable. This is a “label” that represents a value, in this case the characterization is value1 and it represents the accomplished cardinal (integer) 12. It is an accumulation alleged value1 and it is according to 12.

We’re afresh analysis the TextView by adage that we appetite to actualize a basal TextView, which is action to represent the TextView with the ID “Number1” from our blueprint file. Afresh we are ambience the argument of that TextView to be whatever value1 represents. This is a TextView, alleged Number1 and the antecedent is R.id.Number1.

Then we can admission a ‘feature’ of our TextView to say “setText.”

The acumen we say “” value1 is that TextViews apprehend strings of characters, not numbers. By appliance those abandoned citation marks, we are adage ‘no text, additional the number’.

We can do the aforementioned affair for Number2 in the aforementioned way.

You ability be apprehensive what that onSubmitClick was all about. This tells Android Studio we’re action to add some curve of cipher to accept for clicks on that button and we will accumulation those calm as a adjustment alleged “onSubmitClick.”

Anything in onCreate happens aback the app starts up and annihilation in onSubmitClick happens aback the abide button is clicked (because we authentic the adjustment in the architecture view)! Note admitting that we charge to acquisition our angle afresh in adjustment to admission them here.

What happens aback addition clicks on this button?

First, we appetite to analysis what cardinal they accept entered into the EditText. Then, if that cardinal is according to value1 value2, we will acquaint them they got it actual by afterlight the Answer TextView. If they got it incorrect, afresh we will amend the appearance to reflect this while assuming what it should accept been.

This agency analysis our views, converting integers (numbers) into strings (words) and aback again, and additionally appliance an “If” account in adjustment to analysis if the amount provided is correct. The accomplished affair looks like this:

This won’t run aloof yet though, because we can’t admission value1 or value2 – they’re in a altered method. To fix this problem, pop them alfresco the onCreateMethod and now they’ll be accessible to advertence anywhere in your code. We abominably can’t do the aforementioned affair for our buttons and argument angle because we don’t acquaint Android area to acquisition the angle until the onCreate executes.

We’re accepting the TextView and the EditText as we accept done before. Afresh we’re creating an accumulation alleged userAnswer which uses “getText” to retrieve the argument from Attempt and parseInt in adjustment to about-face those characters into a number.

An if account works aloof like in Excel. As continued as the argumentation central the brackets is true, afresh the cipher in the coiled brackets will be executed. So as continued as userAnswer is the aforementioned as value1 value2 (we acclimated two equals signs actuality because Java), afresh we set the Answer to ‘”Correct!”

Otherwise, the brackets that chase the chat “else” will comedy out.

Don’t anguish about all this if it seems complicated — you can either about-face architect this cipher or aloof acquisition the accordant commands and what they all do with a little Googling. Account through it may advice you accept the argumentation though.

The absolute cipher should now attending like this:

Try and run it by active your Android accessory into your computer. Accomplish abiding that you have  USB debugging angry on afore hitting play. You can additionally analysis it on an adversary if you accept set one up.

If you did aggregate right, afresh you should now accept a actual basal algebraic game. Aback I say basic, I’m not kidding— there’s alone one question!

We can change that if we want. It would alone booty allowance the argument anniversary time the user clicked ‘Submit’ and alteration the numbers to accidental values. I’m action to leave you with the cipher to do that. You should be able to amount it out from there!

Tip: The cipher has been added to a new adjustment of our own creation, which can afresh be referred to anywhere in the cipher artlessly by referencing it by name.

Editor's Pick

the actual best way to apprentice is by doing

This architecture appearance will acquiesce you to annoyance and bead elements assimilate the awning to set them out about you like.

Anything in onCreate happens aback the app starts up and annihilation in onSubmitClick happens aback the abide button is clicked

Finding your way around

Creating your views

Naming and customizing views

Starting java

Adding interaction

Final touches

setContentView(R.layout.activity_main);
Int value1 = 12;
TextView Number1 = findViewById(R.id.Number1);
Number1.setText(“”   value1);
public abandoned onSubmitClick (View view){
    TextView Acknowledgment = findViewById(R.id.Answer);
    EditText Attempt = findViewById(R.id.Attempt);
    int userAnswer = Integer.parseInt(Attempt.getText().toString());
    if(userAnswer == value1 value2) {
        Answer.setText("Correct!");

    } abroad {
        Answer.setText("Wrong, the actual acknowledgment was: "   (value1 value2));
    }

}
public chic MainActivity extends AppCompatActivity {

    int value1 = 12;
    int value2 = 64;

    @Override
    adequate abandoned onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView Number1 = findViewById(R.id.Number1);
        Number1.setText("" value1);
        TextView Number2 = findViewById(R.id.Number2);
        Number2.setText("" value2);

    }
    accessible abandoned onSubmitClick (View view){
        TextView Acknowledgment = findViewById(R.id.Answer);
        EditText Attempt = findViewById(R.id.Attempt);
        int userAnswer = Integer.parseInt(Attempt.getText().toString());
        if(userAnswer == value1 value2) {
            Answer.setText("Correct!");

        } abroad {
            Answer.setText("Wrong, the actual acknowledgment was: "   (value1 value2));
        }

    }
}

public chic MainActivity extends AppCompatActivity {

    int value1;
    int value2;

    @Override
    adequate abandoned onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setNewNumbers();
    }

    accessible abandoned onSubmitClick (View view){
        TextView Acknowledgment = findViewById(R.id.Answer);
        EditText Attempt = findViewById(R.id.Attempt);
        int userAnswer = Integer.parseInt(Attempt.getText().toString());
        if(userAnswer == value1 value2) {
            Answer.setText("Correct!");

        } abroad {
            Answer.setText("Wrong, the actual acknowledgment was: "   (value1 value2));
        }
        setNewNumbers();

    }

    clandestine abandoned setNewNumbers () {
        Accidental r = new Random();
        value1 = r.nextInt(999);
        value2 = r.nextInt(999);
        TextView Number1 = findViewById(R.id.Number1);
        Number1.setText("" value1);
        TextView Number2 = findViewById(R.id.Number2);
        Number2.setText("" value2);
        EditText Attempt = findViewById(R.id.Attempt);
        Attempt.setText("");
        
    }
}

Comments