반응형




안드로이드 체크박스를 이용하여 액티비티간 값 전달하기


필요한 코드만 적어서 이대로 실행하면 에러가 나므로 알맞게 수정이 필요함


check.xml 에 체크박스 선언



<CheckBox
    android:id="@+id/option1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="15sp" />

<CheckBox
    android:id="@+id/option2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="15sp" />



CheckActivity.java 에서 체크했을 때 동작 코드 추가


public class CheckActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// 액티비티 생성 setContentView(R.layout.check);// check.xml //버튼 선언 Button button=(Button)findViewById(R.id.button_result); button.setOnClickListener(this); // option1 체크박스가 눌렸을 때 findViewById(R.id.option1).setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Checked(v); // 체크되었을 때 동작코드 } }); // option2 체크박스가 눌렸을 때 findViewById(R.id.option2).setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Checked(v); // 체크되었을 때 동작코드 } }); } public String Checked(View v) { // 체크되었을 때 동작할 메소드 구현 // TODO Auto-generated method stub CheckBox option1 = (CheckBox) findViewById(R.id.option1); // option1체크박스 // 선언 CheckBox option2 = (CheckBox) findViewById(R.id.option2); // option1체크박스 // 선언 String resultText = ""; // 체크되었을 때 값을 저장할 스트링 값 if (option1.isChecked()) { // option1 이 체크되었다면 resultText = "option1"; } if (option2.isChecked()) { resultText = "option2"; // option2 이 체크되었다면 } return resultText; // 체크된 값 리턴 } @Override public void onClick(View v) { if (v.getId() == R.id.button_result) { //button_result 이라는 버튼이 생성되었다고 가정. Intent it = new Intent(this, MainActivity.class); // MainActivity.java로 보내기 위한 인텐트 선언 it.putExtra("it_check", Checked(v)); // it_check 라는 이름하에 체크된 값을 전달 startActivity(it); // MainActivity.java를 실행하면서 값을 전달 } } }



MainActivity.java에서 값 전달 받기



public class MainActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);//액티비티 생성 setContentView(R.layout.main);//main.xml Intent it=getIntent(); //인텐트 받기 선언 //이전에 보냈던 it_check의 값을 받아 str에 저장 String str= it.getStringExtra("it_check"); //즉 str = "option1" 또는 "option2" 가 들어있음 //이 값을 이용하여 필요한 동작 구현 if(str.equals("option1"){ //str 값이 option1 이라면 //필요한 동작 코드 작성 }else if(str.equals("option2"){ //str 값이 option2 라면 //필요한 동작 코드 작성 } } }


동작 순서는 check.xml -> CheckActivity.java -> MainActivity.java 이렇게 된다






반응형

+ Recent posts