一、点击事件
1、创建内部类方法
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
button.setOnClickListener(new MyClick());
}
public class MyClick implements View.OnClickListener {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "我被点击了", Toast.LENGTH_SHORT).show();
}
}
}
2、创建匿名类方法
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(SecondActivity.this, "我被点击了", Toast.LENGTH_SHORT).show();
}
});
}
}
3、activity实现OnClickListener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "我被点击了", Toast.LENGTH_SHORT).show();
}
}
4、xml布局添加回调方法
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="xml方法回调点击事件"
android:onClick="btnClick"
/>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClick(View view) {
Toast.makeText(this, "我被点击了", Toast.LENGTH_SHORT).show();
}
}
二、长按点击事件
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
button = findViewById(R.id.longBtn);
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Toast.makeText(MainActivity.this, "我被点击了", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}