Skip to content

Instantly share code, notes, and snippets.

@Chetan496
Created July 30, 2016 11:52
Show Gist options
  • Save Chetan496/721736d09ee7e091d69032dd23aca2ac to your computer and use it in GitHub Desktop.
Save Chetan496/721736d09ee7e091d69032dd23aca2ac to your computer and use it in GitHub Desktop.
Basic Event Handling in Android
package com.example.mac.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.text1) ; /*this will contain the name */
final TextView text2 = (TextView) findViewById(R.id.text2) ; /*this will contain the welcome message */
final Button button = (Button) findViewById(R.id.button) ;
/*This is an example of using Event Listeners in Android */
button.setOnClickListener( new Button.OnClickListener() {
public void onClick(View view){
Log.i(Constants.INFO, "Id of the view is "+ (view.getId() == R.id.button)) ;
final String name = editText.getText().toString() ;
if(name.trim().isEmpty()){
/*TODO: give an error on the UI. Name cannot be empty */
editText.setError("You have to enter a name");
return;
}
final String message = "Hello "+name+" !" ;
text2.setText(message);
}
} );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment