android 实现button的点击

来源:互联网 发布:淘宝sdr是什么意思 编辑:程序博客网 时间:2024/05/21 21:49

android实现button的触发有三种方法

1.直接定义button的setOnClickListener属性

protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    start_srv = (Button)findViewById(R.id.startsrv);    start_srv.setOnClickListener(new View.OnClickListener(){        @Override                public  void onClick(View v) {            Intent startIntent;            startIntent = new Intent(MainActivity.this, MyService.class);            startService(startIntent);        }    });
2.外部类实现事件监听器接口
public class MainActivity extends AppCompatActivity  implements  View.OnClickListener{    private Button start_srv;    private Button stop_srv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        start_srv = (Button)findViewById(R.id.startsrv);        start_srv.setOnClickListener(this);
stop_srv = (Button)findViewById(R.id.stopsrv);
        stop_srv.setOnClickListener(this);
     };
    
@Overridepublic void onClick(View v) {    switch (v.getId()) {        case R.id.startsrv:            Intent startIntent;            startIntent = new Intent(MainActivity.this, MyService.class);            startService(startIntent);            break;        case R.id.stopsrv:            Intent stopIntent = new Intent(MainActivity.this, MyService.class);            stopService(stopIntent);            break;        default:            break;    }}
3.内部类实现事件监听接口
public class MainActivity extends AppCompatActivity  {    private Button start_srv;    private Button stop_srv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        start_srv = (Button)findViewById(R.id.startsrv);        start_srv.setOnClickListener(new ClickEvent());        stop_srv = (Button)findViewById(R.id.stopsrv);        stop_srv.setOnClickListener(new ClickEvent());    };    class ClickEvent implements View.OnClickListener {        @Override        public void onClick(View v) {            switch (v.getId())            {                case R.id.startsrv:                    Intent startIntent;                    startIntent = new Intent(MainActivity.this, MyService.class);                    startService(startIntent);                    break;                case R.id.stopsrv:                    Intent stopIntent = new Intent(MainActivity.this,MyService.class);                    stopService(stopIntent);                    break;                default:                    break;            }        }    }