skip to Main Content

I am trying to make a toast appear when I click a button. I have already set the button’s on click to be the ‘cli function’. However when I press the button nothing appears. Could you please help me.

enter image description here

enter image description here

enter image description here

3

Answers


  1. In xml,make sure you declared onClick in your Button attribute

    android:onClick="cli"
    

    Also, in onCreate, declare your Button id

    Button button = (Button) findViewById(R.id.button);
    
    Login or Signup to reply.
  2. Don’t use onClick on XML, as it’s buggy and may not work on all versions:

    Buttons onClick Force closes app on Android 4.1 device

    Better do it in code:

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           // code here
       } 
    });
    
    Login or Signup to reply.
  3. Don’t use onClick on XML.

    Use OnClickListeners. Here is the code:

    Button button = findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
       public void onClick(View v) {
           cli(v);
       } 
    });
    

    The above code will help you with detecting clicks on the button. Prefer not using android:onClick in XML.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search