We're gonna do some push ups. :)) |
So, after creating a new project, we will modify two files. The main activity file, which is in this case, the AndroidButtons.java and the layout file which is the main.xml
AndroidButtons.java
package com.example.AndroidButtons; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class AndroidButtons extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { View.OnClickListener handler = new View.OnClickListener(){ public void onClick(View v) { //we will use switch statement and just //get thebutton's id to make things easier switch (v.getId()) { case R.id.ShowToastBtn: //toast will be shown Toast.makeText(getBaseContext(), "You Clicked Show Toast Button!", Toast.LENGTH_SHORT).show(); break; case R.id.FinishBtn: //program will end finish(); break; } } }; //we will set the listeners findViewById(R.id.ShowToastBtn).setOnClickListener(handler); findViewById(R.id.FinishBtn).setOnClickListener(handler); }catch(Exception e){ Log.e("Android Button Tutorial", e.toString()); } } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="98px" android:layout_height="wrap_content" android:text="Show Toast" android:id="@+id/ShowToastBtn"> </Button> <Button android:layout_width="98px" android:layout_height="wrap_content" android:text="Finish" android:id="@+id/FinishBtn"> </Button> </LinearLayout>
When you run this script it will look like this:
When you click the "Show Toast" Button, it will look like this:
When you click "Finish", obviously, the program will end. Haha!
The Code of a Ninja Resources
For FREE programming tutorials, click the red button below and subscribe! :)
website