Mega Code Archive

 
Categories / Android / UI
 

Load Button from layout xml file and add action listener

package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Test extends Activity {   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.main);       //Retrieve the button object       Button myButton = (Button)findViewById(R.id.myButton);       //Attach the listener       myButton.setOnClickListener(clickListener);   }   //Listener object to handle the click events   View.OnClickListener clickListener = new View.OnClickListener() {       public void onClick(View v) {       }   }; } //main.xml <?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android"   android:id="@+id/myButton"   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="My Button" />