1.MyHobby.java
package com.example.hobby;
//import java.security.PublicKey;
//import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MyHobby extends Activity{
private CheckBox hobby1,hobby2,hobby3;
private Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkhobby);
//初始化
submit=(Button) findViewById(R.id.submit);
hobby1=(CheckBox) findViewById(R.id.checkBox1);
hobby2=(CheckBox) findViewById(R.id.checkBox2);
hobby3=(CheckBox) findViewById(R.id.checkBox3);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Toast toast=Toast.makeText(MyHobby.this, "你选择了:"+getResult(), Toast.LENGTH_SHORT);
toast.show();
}
});
// 定义一个有名字的监听器类。之所以不用匿名内部类形式,是因为有多个控件都要使用这同一个监听器
OnCheckedChangeListener listener=new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast toast=Toast.makeText(MyHobby.this, "你选择了:"+getResult(), Toast.LENGTH_SHORT);
toast.show();
}
};
hobby1.setOnCheckedChangeListener(listener);
hobby2.setOnCheckedChangeListener(listener);
hobby3.setOnCheckedChangeListener(listener);
}
// 获取多选项中被勾选的结果。利用isChecked()方法来判断哪个选项被勾选
private String getResult(){
StringBuilder sb=new StringBuilder();
if(hobby1.isChecked()){
sb.append(hobby1.getText());
}
if(hobby2.isChecked()){
sb.append(hobby2.getText());
}
if(hobby3.isChecked()){
sb.append(hobby3.getText());
}
return sb.toString();
}
}
2.checkhobby.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="爱好:" />
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="游泳" />
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="唱歌" />
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="阅读" />
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交" />
3.具体问题
虚拟装置管理器点击这个项目的提交按钮,并没有出现预期的Toast语句