Hello all,
Today, I introduce one more Android tip, a basic simple Android Application, basic rectangular. I will develop a simple application to calculate the parimeter and the area of a rectangular.
Jump Ahead To:
Purpose of this application:
- Be familiar with Android environment development.
- Be familiar with an Android project organization.
- Create an Android project, basic layout.
- Know about basic java.
- Know about three basic widgets: TextView, EditText and Button.
- Know about Click event for Button.
Let’s do it
I. IN ACTIVITY_MAIN.XML
- Create 2 Edit Text for 2 values: Length and Width
1
2
3
4
5
|
<span style=“color: #000000;”><EditText
android:id=“@+id/editLength”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
/></span>
|
1
2
3
4
5
|
<span style=“color: #000000;”><EditText
android:id=“@+id/editWidth”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
/></span>
|
- Create a Button to calculate the perimeter and the area
1
2
3
4
5
6
|
<span style=“color: #000000;”><Button
android:id=“@+id/btnResult”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Result”
/></span>
|
- Create a Text View to show the result.
1
2
3
4
5
|
<span style=“color: #000000;”><TextView
android:id=“@+id/txtResutl”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
/></span>
|
II. IN MAINACTIVITY.JAVA
- Create Text View, Edit Text and Button.
1
2
3
|
<span style=“color: #000000;”>TextView tv_result;
Button btn_result;
EditText edt_length, edt_width;</span>
|
- In btn_result, add setOnClickListener event for the button.
1
2
3
4
5
6
7
8
|
<span style=“color: #000000;”>btn_result.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});</span>
|
- In onClick class, I create length and width variables, get the values from Edit Text and add to length and width variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<span style=“color: #000000;”>btn_result.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int length = Integer.parseInt(edt_length.getText().toString());
int width = Integer.parseInt(edt_width.getText().toString());
int perimeter = (length + width) * 2;
int area = length * width;
tv_result.setText(“The Perimeter is “ + perimeter + ” and the Area is “ + area);
}
});</span>
|
- Create perimeter and area variables.
1
2
|
<span style=“color: #000000;”>int perimeter = (length + width) * 2;
int area = length * width;</span>
|
- Final, I add the result to the Text View.
1
|
<span style=“color: #000000;”>tv_result.setText(“The Perimeter is “ + perimeter + ” and the Area is “ + area);</span>
|
sdsd