Android: Button OnClickListener does not working

不想你离开。 提交于 2019-12-05 05:11:20

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;
            }

        }
    }
}

You forget to implement onClickListener in your Activity.

Implement it and then try :)

public class Menu extends Activity implements onClickListener
    View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
     // the 1st button
     }
    }
    View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
     //the 2nd button
     }

You have to declare your buttons like this:

Button loginbutton = (Button)findViewById(R.id.butlogin);
    loginbutton.setOnClickListener(this);

    Button recordbutton = (Button)findViewById(R.id.butrecordts);
    recordbutton.setOnClickListener(this);

    Button viewbutton = (Button)findViewById(R.id.butviewts);
    viewbutton.setOnClickListener(this);

    Button projectsbutton = (Button)findViewById(R.id.butprojects);
    projectsbutton.setOnClickListener(this);
GrIsHu

You have just forgotten to implement the onClickListener in your activity:

public class Menu extends Activity implements OnClickListener { <----Check out this line ............................ }

Aha

Try changing this line

 View loginbutton = findViewById(R.id.butlogin);

to

 Button  loginbutton = (Button)findViewById(R.id.butlogin);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!