Button Tutorial: Android Programming

2017-10-23 1

Demonstration on how to create a button in an Android application. Walks through creating the button and writing the Java code to make it interive. \r
\r
Steps and Java code included below in this description.\r
\r
Steps\r
===============\r
1. Create the button on the UI (xml).\r
2. Get a reference to the button (java)\r
3. Register a listener (java) [code below]:\r
myButton.setOnClickListener(.)\r
Our listener is an anonymous class implementing:\r
View.OnClickListener\r
We implement its only function: onClick()\r
(this is where we put our code).\r
\r
Aside: \r
Toast: a message that pops up on the screen.\r
\r
\r
Java Code:\r
==============================\r
public class MainActivity extends Activity {\r
private final String TAG = DemoButtonApp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ivity_main); setupMessageButton(); }\r
\r
private void setupMessageButton() {\r
// 1. Get a reference to the button.\r
Button messageButton = (Button) findViewById(R.id.btnDisplayMessage); // 2. Set the click listener to run my code.\r
View.OnClickListener myListener = new View.OnClickListener() {\r
@Override\r
public void onClick(View v) { Log.i(TAG, You clicked the button!); Toast.makeText( MainActivity.this, You clicked it!, Toast.LENGTH_LONG ).show();\r
}\r
};\r
messageButton.setOnClickListener(myListener);\r
} \r
}\r
\r
\r
\r
Demo created using the Android Development Tools, build v21.0.0-519525

Free Traffic Exchange