Button設定點選事件的四種方式
阿新 • • 發佈:2018-12-01
Button的點選事件可以有好多種你知道麼?
第一種(匿名內部類):
private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_day5); btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("flag","你點了我"); } }); }
第二種(內部實現介面):
private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_day5); btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(new MyLinstenter()); } class MyLinstenter implements View.OnClickListener { @Override public void onClick(View v) { btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("flag", "你點了我哦!"); } }); } }
第三種(外部類實現介面):
private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_day5); btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(new MyLinstenter(btn1)); } } class MyLinstenter implements View.OnClickListener { private Button btn1; public MyLinstenter(Button btn1) { this.btn1 = btn1; } @Override public void onClick(View v) { btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("flag", "你點了我哦!"); } }); }
第四種(使用本類物件實現介面):
public class day5 extends AppCompatActivity implements View.OnClickListener{
private Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day5);
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Log.i("flag", "你點了我哦!");
}
}