当存在做个Button时,就可以通过重写 onClick 方法实现Button点击事件的封装,便于管理。
package com.example.love.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private View view;
private Button button1;
private Button button2;
private Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (View) this.findViewById(R.id.relativeLayout);
// view.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Toast.makeText(MainActivity.this, "Click me!!!!", Toast.LENGTH_LONG).show();
// }
// });
button1 = (Button) this.findViewById(R.id.button1);
button2 = (Button) this.findViewById(R.id.button2);
button3 = (Button) this.findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
// button1.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Toast.makeText(MainActivity.this, "点击按钮Button", Toast.LENGTH_LONG).show();
// }
// });
// // OnLongClickListener包含OnClickListener事件
// // 所以在OnLongClickListener中处理了,就不要在 OnClickListener 中处理了
// button1.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// Toast.makeText(MainActivity.this, "长按点击按钮Button", Toast.LENGTH_LONG).show();
// return false;
// }
// });
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Toast.makeText(MainActivity.this, "Click me!!!!", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(MainActivity.this, "Click me!!!!", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(MainActivity.this, "Click me!!!!", Toast.LENGTH_SHORT).show();
break;
}
}
}