public class MainActivity extends Activity implements View.OnClickListener{
private Button button;
private EditText edittext;
private ImageView imageView;
private ProgressBar progressBar;
private int flag = 0;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private ProgressBar progressBar2;
@Override
//初始化资源
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
edittext = (EditText)findViewById(R.id.edittext);
imageView = (ImageView)findViewById(R.id.imageView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button2 = (Button)findViewById(R.id.button2);
button3 = (Button)findViewById(R.id.button3);
//设置按钮的事件
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
imageView.setOnClickListener(this);
progressBar2 = (ProgressBar)findViewById(R.id.progressBar2);
button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(this);
button5 = (Button)findViewById(R.id.button5);
button5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
//把edittext中输入的文本显示为提示
String inputtext = edittext.getText().toString();
Toast.makeText(MainActivity.this,inputtext,Toast.LENGTH_SHORT).show();
break;
case R.id.imageView:
//点击后log1和log2互相切换
if (flag == 0) {
imageView.setImageResource(R.drawable.log2);
flag = 1;
}
else {
imageView.setImageResource(R.drawable.logo1);
flag = 0;
}
break;
case R.id.button2:
//点击后,进度条消失
if(progressBar.getVisibility() == View.GONE){
progressBar.setVisibility(View.VISIBLE);
}else {
progressBar.setVisibility(View.GONE);
}
break;
//点击后,进度条增加10%
case R.id.button3:
int progress = progressBar2.getProgress();
progress = progress + 10;
progressBar2.setProgress(progress);
break;
case R.id.button4:
//弹出提示框,显示This is a dialog
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("This is a dialog");
dialog.setMessage("something important");
dialog.setCancelable(false);
dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
break;
case R.id.button5:
//弹出加载进度条
ProgressDialog progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setTitle("This is a ProgressDialog");
progressdialog.setMessage("Loading...");
progressdialog.setCancelable(true);
progressdialog.show();
default:
break;
}
}
}
Android程序:多按钮点击事件的常用功能实现
最新推荐文章于 2023-07-22 14:30:38 发布