Button Tutorial: Android Programming @DrBFraser
Button Tutorial: Android Programming  @DrBFraser
Uploaded February 2013 | Updated November 2026, 3 hours ago
Demonstration on how to create a button in an Android application. Walks through creating the button and writing the Java code to make it interactive.

Steps and Java code included below in this description.

Steps
===============
1. Create the button on the UI (xml).
2. Get a reference to the button (java)
3. Register a listener (java) [code below]:
myButton.setOnClickListener(...)
Our listener is an anonymous class implementing:
View.OnClickListener
We implement its only function: onClick()
(this is where we put our code).

Aside:
Toast: a message that pops up on the screen.


Java Code:
==============================
public class MainActivity extends Activity {
private final String TAG = "DemoButtonApp";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setupMessageButton();
}

private void setupMessageButton() {
// 1. Get a reference to the button.
Button messageButton = (Button) findViewById(R.id.btnDisplayMessage);

// 2. Set the click listener to run my code.
View.OnClickListener myListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "You clicked the button!");
Toast.makeText(
MainActivity.this,
"You clicked it!",
Toast.LENGTH_LONG
).show();
}
};
messageButton.setOnClickListener(myListener);
}
}



Demo created using the Android Development Tools, build v21.0.0-519525
Button Tutorial: Android ProgrammingSubversive: Ignore bin/ and gen/ foldersChecking out an existing project: Git & EclipsePost changes to AppServer: Android ProgrammingListView with Images and Text: Android ProgrammingConfigure a VMWare Player VMReturn Data From Activity: Android ProgrammingModel / View Separation: Java for ProgrammersCreating a Java project and JUnit 3 test code in EclipseRun Java from Jar: IntelliJ TerminalInstall and Run C++ in Visual Studio Code (Windows) v2VS Code Debugging a Simple C++ Program
Brian Fraser |

Button Tutorial: Android Programming

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER