单击事件 Toast提示信息框方(android studio)
程序员文章站
2022-07-14 13:42:16
...
方法一:使用setOnClickListener()方法
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 {
Button button1;
Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1); //绑定按钮
button2 = findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//单击登录按钮出现登录成功信息提示框
Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//单击取消按钮出现退出信息提示框
Toast.makeText(MainActivity.this, "退出", Toast.LENGTH_SHORT).show();
}
});
}
}
点击登录按钮后
点击取消按钮后
方法二:实现View.OnClickListener接口
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{ //实现View.OnClickListener接口
Button button1;
Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
//实现View.OnClickListener接口
@Override
public void onClick(View v) {
switch (v.getId()){ ,
case R.id.button1:
Toast.makeText(this, "登录", Toast.LENGTH_SHORT).show();
case R.id.button2:
Toast.makeText(this, "退出", Toast.LENGTH_SHORT).show();
}
}
}
方法三:在xml里面配置
现在xml里面写上
然后再
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{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login (View v){
Toast.makeText(this, "登录3", Toast.LENGTH_SHORT).show();
}
public void cancel(View v){
Toast.makeText(this, "退出3", Toast.LENGTH_SHORT).show();
}
}