Button setonclicklistener error

前端 未结 6 1838
感情败类
感情败类 2020-12-31 23:43

I am having a problem right now with setOnClickListener.

When i put this following line:

button.setOnClickListener(this);
相关标签:
6条回答
  • 2021-01-01 00:06

    Check if in the class definition there is implements OnClickListener

    0 讨论(0)
  • See if the code below works for you...

    button.setOnClickListener(new OnClickListener() {              
      @Override
      public void onClick(View v) 
      {
          Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_LONG).show();
      }    
    });      
    

    Remember to add }); at the end.

    0 讨论(0)
  • 2021-01-01 00:21

    Type View.onClickListener instead of Button on ClickListener

    0 讨论(0)
  • 2021-01-01 00:24

    Although it's been a long time, thought it might help others who have this problem, it took me many trials to get it right. But i think what finally solved my problem was setting the clickable attribute of a button in the layout's xml to true.
    Code sample:

    <Button android:text="Button" android:id="@+id/button1"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:clickable="true">
    </Button>
    

    Further, if you would've looked at the DDMS perspective, you would've seen that the cause of the error was NullPointerException, which ofcourse was showing because clickable wasn't set. Correct me if i am wrong.

    0 讨论(0)
  • 2021-01-01 00:25

    another possible reason ( happened to me ) is your activity must implement OnClickListener

    public class MainActivity extends Activity implements OnClickListener ...
    
    0 讨论(0)
  • 2021-01-01 00:29

    For defining button click event in android, You can try the below code:

    public class Main_Activity extends Activity {
    
    
        private Button myButton;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        myButton = (Button) findViewById(R.id.Button01);
        myButton.setOnClickListener(new Button_Clicker());
    }
    
    class Button_Clicker implements Button.OnClickListener
    {
        @Override
        public void onClick(View v) {
    
           if(v==myButton)
           {
                    Toast.makeText(v.getContext(), "Hello!! button Clicked", Toast.LENGTH_SHORT).show();
    
           }    
    }
    }
    

    }

    0 讨论(0)
提交回复
热议问题