Android: Button OnClickListener does not working
31,302
Solution 1
Yes, The Problem is in Declaration of button, write below code instead of your code, it will solve your problem.
public class Menu extends Activity implements OnClickListener{
Button loginbutton, recordbutton, viewbutton, projectsbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
loginbutton = (Button) findViewById(R.id.butlogin);
loginbutton.setOnClickListener(this);
recordbutton = (Button) findViewById(R.id.butrecordts);
recordbutton.setOnClickListener(this);
viewbutton = (Button) findViewById(R.id.butviewts);
viewbutton.setOnClickListener(this);
projectsbutton = (Button) findViewById(R.id.butprojects);
projectsbutton.setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId())
{
case R.id.butlogin:
{
//open login screen
Intent i = new Intent(this, login.class);
startActivity(i);
break;
}
case R.id.butrecordts:
{
break;
}
case R.id.butviewts:
{
break;
}
case R.id.butprojects:
{
break;
}
}
}
}
Solution 2
You forget to implement onClickListener
in your Activity.
Implement it and then try :)
public class Menu extends Activity implements onClickListener
Author by
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
I have created this activity that should allow me to open a new activity once a button has been pressed.
However the OnClickListener does not seem to be working.
Am I declaring the buttons wrong?
Can someone me out?
public class Menu extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menu); View loginbutton = findViewById(R.id.butlogin); loginbutton.setOnClickListener(this); View recordbutton = findViewById(R.id.butrecordts); recordbutton.setOnClickListener(this); View viewbutton = findViewById(R.id.butviewts); viewbutton.setOnClickListener(this); View projectsbutton = findViewById(R.id.butprojects); projectsbutton.setOnClickListener(this); } public void onClick(View v){ switch(v.getId()) { case R.id.butlogin: { //open login screen Intent i = new Intent(this, login.class); startActivity(i); break; } case R.id.butrecordts: { break; } case R.id.butviewts: { break; } case R.id.butprojects: { break; } } }
-
AndroidLearner over 11 yearssee my edited answer.Just replace this line with your code :)
-
Admin over 11 yearsThank you, this has resolved the problem. However, in doing so the app stops responding once a button is pressed.
-
AndroidLearner over 11 years@HydarRoze If my answer helpful to you,don't forget to accept and upvote it :)
-
Admin over 11 yearsIt's asking if I have declared the activity in my android manifest. I have done so.
-
Dipak Keshariya over 11 years@HydarRoze OK, no problem.
-
wesley franks almost 5 yearsThis helped me! Thank you. I didn't set the onclicklistener for the view itself after setting the view.