How to catch a click event on a button?

前端 未结 7 938
[愿得一人]
[愿得一人] 2020-12-05 04:28

.NET Developer here just getting started with Eclipse and Android.

Can someone show me in the simplest way possible, with the absolute fewest lines of code, how to D

7条回答
  •  不知归路
    2020-12-05 05:11

    All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.

    An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.

    package com.pointerunits.helloworld;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class MainActivity extends Activity implements OnClickListener {
       private Button login;
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          login = (Button)findViewById(R.id.loginbutton);
          login.setOnClickListener((OnClickListener) this);
          Log.i(DISPLAY_SERVICE, "Activity is created");
    
       }    
    
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
    
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
        }
    
       @Override
       public void onClick(View v) {
         Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
       }
    }
    

提交回复
热议问题