Now its time go to the source code.
When we created the project, we put a name to the Activity, I used “Calculator”, so this is the main file of the Application.
Here, we can find the onCreate method. This is the method that its called when we create the Activity, so here we will initialize all variables.
First, we are going to create the widgets in the Java Code, using the following line-format:
input1 = (EditText) findViewById(R.id.input1);
Where input1 is a EditText type variable, and with the findViewById(R.id.input1) we associate this variable to the widget we create in the XML code (main.xml).
We create one variable for each widget: input1, input2, solution, operator and all buttons.
For buttons, we are going to assign a onClick event to each one. In this way, we will control when this buttons are clicked.
plusButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//TODO
}
});
We create a OnClickListener, this element “listen” clicks events on this button (plusbutton) and when a click happens, the “onClick” method is executed.
Inside the onClick method we are going to put just a simple line:
operator.setText("+");
This is: “To the widget 'operator' (the one between the two Edits texts), assign the text '+'”. In the screen, when the "+" button is clicked, a "+" simbol will apear between the two EditTexts. I do this just to show how we can change the elements of the screen with the code.
The others buttons are the same, just change witch button calls the OnClick and the value inside the operator.setText().
The whole source code is here:
http://code.google.com/p/android-projects/source/browse/Calculator/src/com/bright/hub/Calculator/Calculator.java
When we arrive to the “equalbutton” we are going to do something different.
We are going to create some filter and show a Alarm when, for example, the inputs are empty and we press the “=” button.
Creating the Alarm is so simple:
show = new AlertDialog.Builder(mContext)
.setTitle("Error")
.setMessage("Some inputs are empty")
.setPositiveButton("OK", null).show();
Where mContext is the actual Activity, “Error” is the title of the Alert and “Some inputs are empty” is the message. We can add a button with the “Ok” message. And all this is shown, using .show(); method.
Now, we are going to check the value of the “operator”, when we click on the “equal button”, depending on what its on it (“+”,”-”...) we do an operation or other and we put the value on the solution EditText.
if (operator.getText().equals("+")) {
double result = new Double(input1.getText().toString())+ new Double(input2.getText().toString());
solution.setText(Double.toString(result));
The full source code is in my new created Google Code acount:
http://code.google.com/p/android-projects/source/browse/
This is a very simple example, just for learning. In further examples we will complicate the code.