android button listener code example

Example 1: button listener android

public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.my_layout_id);

         final Button button = (Button) findViewById(R.id.my_cool_button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // your handler code here
             }
         });
     }

}

Example 2: android studio button usage

//this for xml file 
<Button  
        android:id="@+id/button"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="109dp"  
        android:text="hello"  
 /> 

//this for java file 
Button btn;
  @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
               //do something
            }  
        }); 
    }

Example 3: button android stdui

Button b = findById();

Example 4: show button selected when clicked

mycodes_Button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mycodes_Button.setPressed(true);
        return true;
    }
});

Tags:

Java Example