先写一个CheckBox和ImageButton的例子,效果如下:
其实ImageButton的用法和普通Button的用法差不多,源码如下:
1 package com.demo;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.Gravity;
6 import android.view.View;
7 import android.view.View.OnClickListener;
8 import android.widget.CheckBox;
9 import android.widget.ImageButton;
10 import android.widget.Toast;
11
12 public class Demo04 extends Activity {
13 /** Called when the activity is first created. */
14 @Override
15 public void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.main);
18
19 // 获取按钮
20 ImageButton btnOK = (ImageButton) this.findViewById(R.id.btnOK);
21 // 为按钮的单击定义响应事件的类
22 btnOK.setOnClickListener(OnBtnOKClick);
23 }
24
25 // 定义一个处理按钮单击事件的类
26 private OnClickListener OnBtnOKClick = new OnClickListener()
27 {
28 // 在类中定义单击事件的处理函数
29 public void onClick(View v)
30 {
31 String str = "";
32 CheckBox cbxGroup = (CheckBox) Demo04.this.findViewById(R.id.cbxGroup);
33 CheckBox cbxSingle = (CheckBox) Demo04.this.findViewById(R.id.cbxSingle);
34
35 if(!cbxGroup.isChecked() && !cbxSingle.isChecked())
36 str = "您至少要选择一个答案!";
37
38 if(cbxGroup.isChecked())
39 str = "您喜欢的旅游方式为:【随团旅游】";
40 if(cbxSingle.isChecked())
41 {
42 if(str.length()>0)
43 str += "和【自助游】";
44 else
45 str = "您喜欢的旅游方式为:【自助游】";
46 }
47
48 Toast toast = Toast.makeText(Demo04.this, str, Toast.LENGTH_SHORT);
49 toast.setGravity(Gravity.CENTER, 0, 0);
50 toast.show();
51 }
52 };
53 }
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.Gravity;
6 import android.view.View;
7 import android.view.View.OnClickListener;
8 import android.widget.CheckBox;
9 import android.widget.ImageButton;
10 import android.widget.Toast;
11
12 public class Demo04 extends Activity {
13 /** Called when the activity is first created. */
14 @Override
15 public void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.main);
18
19 // 获取按钮
20 ImageButton btnOK = (ImageButton) this.findViewById(R.id.btnOK);
21 // 为按钮的单击定义响应事件的类
22 btnOK.setOnClickListener(OnBtnOKClick);
23 }
24
25 // 定义一个处理按钮单击事件的类
26 private OnClickListener OnBtnOKClick = new OnClickListener()
27 {
28 // 在类中定义单击事件的处理函数
29 public void onClick(View v)
30 {
31 String str = "";
32 CheckBox cbxGroup = (CheckBox) Demo04.this.findViewById(R.id.cbxGroup);
33 CheckBox cbxSingle = (CheckBox) Demo04.this.findViewById(R.id.cbxSingle);
34
35 if(!cbxGroup.isChecked() && !cbxSingle.isChecked())
36 str = "您至少要选择一个答案!";
37
38 if(cbxGroup.isChecked())
39 str = "您喜欢的旅游方式为:【随团旅游】";
40 if(cbxSingle.isChecked())
41 {
42 if(str.length()>0)
43 str += "和【自助游】";
44 else
45 str = "您喜欢的旅游方式为:【自助游】";
46 }
47
48 Toast toast = Toast.makeText(Demo04.this, str, Toast.LENGTH_SHORT);
49 toast.setGravity(Gravity.CENTER, 0, 0);
50 toast.show();
51 }
52 };
53 }