0 works

How to handle Button Click?


dashboard+ Project

Posted by @Awais malik #android

Step 0: First of all we get reference of button from layout

public class MainActivity extends AppCompatActivity{ 
    private Button mButton;

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = findViewById(R.id.mButton);

       
   }
}
content_copyCopy to Clipboard

Step 1: Now set onClickListner in side onCreate Method

mButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 
                        Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
             }
         });
content_copyCopy to Clipboard

Step 2: Now we look at second method which is on click method. in our resource layout file you have to put following code for button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="buton"
        android:onClick="btnClicked"/>
content_copyCopy to Clipboard

Step 3: now we create that mehod in our class which we want to triger when button clicked

public void btnClicked(View view){
       
                        Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
}
content_copyCopy to Clipboard

More details:

In this tutorial we learn about how to handle actions when user clicks on a button in android. here i will discuss two methods 1: onClickListner 2: onClick method

Code snippet source:

,

>> Browse more code snippets

more_vert