CheckBox, RadioGroup, RadioButton 이벤트 예제

 

(1) activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 <CheckBox
     android:id="@+id/chk1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:checked="true"
     android:text="@string/font1"
     android:layout_alignParentTop="true"
     />

 <RadioGroup
     android:id="@+id/colors"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_below="@id/chk1"
     android:orientation="vertical"  >

 

 <RadioButton
         android:id="@+id/rgRed"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="@string/red"
         android:checked="true"
         />
     <RadioButton
         android:id="@+id/rgBlue"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="@string/blue"
         />
     <RadioButton
         android:id="@+id/rgGreen"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="@string/green"
         />
 </RadioGroup>

  <TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/mymsg"
        android:textSize="20pt"
        android:textColor="#ff0000"
        />
</RelativeLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(2) string.xml ( values폴더 )

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Test04</string>
    <string name="mymsg">Happy Day!</string>
    <string name="font1">글씨 크게</string>
    <string name="red">빨강</string>
    <string name="blue">파랑</string>
    <string name="green">초록</string>

</resources>

 

 

(3) MainActivity.java

package com.example.test04;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends Activity {
    CheckBox chk1;
    TextView txt1;
    RadioGroup rg;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //텍스트뷰, 체크박스에 대한 참조값 얻어오기.
        chk1 = (CheckBox)findViewById(R.id.chk1);
        txt1 = (TextView)findViewById(R.id.txt1);
        rg=(RadioGroup)findViewById(R.id.colors);

 

        //체크박스에 이벤트리스너 등록(체크상태가 바뀔때마다 감지)
        chk1.setOnCheckedChangeListener( new OnCheckedChangeListener() {
            //체크박스를 클랙해서 체크상태가 바뀔때마다 자동 호출
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                //이벤트가 발생된 컴포넌트 id가 chk1이라면 

                if(buttonView.getId()==R.id.chk1){
                    if(isChecked){//체크된 상태라면
                        txt1.setTextSize(40);//텍스트뷰 사이즈 변경
                    }else{
                        txt1.setTextSize(20);
                    }
                }
            }
        });       

 

 

        rg.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {           
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //체크가 된 radio button 아이디
                switch(checkedId){
                //textView의 색상 바꾸기.
                case R.id.rgRed:
                    txt1.setTextColor(Color.RED);break;
                case R.id.rgBlue:
                    txt1.setTextColor(Color.BLUE);break;
                case R.id.rgGreen:
                    txt1.setTextColor(Color.GREEN);break;
                }               
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }   
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Mobile > Android' 카테고리의 다른 글

#07 ( 다음,이전 버튼으로 사진이동하기 )  (0) 2013.02.02
#06 (이미지 뷰)  (0) 2013.02.02
#04( 입력한 값 보여주기 예제 )  (0) 2013.01.28
#03( 합구하기 )  (0) 2013.01.28
#02 ( 시작하기 )  (0) 2013.01.28
로그인 버튼을 클릭하면 입력된 아이디와 비밀번호를 얻어와 토스트로 출력해 보세요.
// 아이디: xxx 비밀번호:xxx

 

(1) activity_main.xml

; activity main의 layout 변경 - Graphical layout에서 화면에 마우스 우측 - change layout - 원하는 layout 선택

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="아이디 입력"
            />
        <EditText android:id="@+id/id"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="비밀번호입력"
            />       
        <EditText android:id="@+id/pwd"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:password="true"
            />
    </LinearLayout>
    <Button android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인"/>
</LinearLayout>

 

 

 

(2) MainActivity.java

; 인터페이스를 구현하지 않고 익명의 내부클래스 사용.

 

package com.example.test03;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
// Quiz
//로그인 버튼을 클릭하면 입력된 아이디와 비밀번호를 얻어와 토스트로 출력해 보세요.
// 아이디: xxx 비밀번호:xxx

public class MainActivity extends Activity {
    EditText id;
    EditText pwd;
    Button btn;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        id = (EditText)findViewById(R.id.id);
        pwd= (EditText)findViewById(R.id.pwd);
        btn= (Button)findViewById(R.id.btn);

 

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strId = id.getText().toString();
                String strPwd= pwd.getText().toString();
                //익명의 내부클래스 사용시 this는 new생성 객체가 되기 때문에 오류가 난다.
                //이때는 MainActivity자신을 의미하기 때문에 MainActivity.this로 넘긴다.
                Toast.makeText(MainActivity.this, "아이디:" + strId + "  비밀번호:" + strPwd, Toast.LENGTH_LONG ).show();
            }
        } );

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }   
}

 

 

'Mobile > Android' 카테고리의 다른 글

#06 (이미지 뷰)  (0) 2013.02.02
#05 ( checkbox, radiobutton )  (0) 2013.01.29
#03( 합구하기 )  (0) 2013.01.28
#02 ( 시작하기 )  (0) 2013.01.28
#01( Android Virtual Device Manager )  (0) 2013.01.28
EditText에 두 수를 입력받아 합을 구하기

 

(1) activity_main.xml

 

 id부여>>

 @+id/idname, @id/idname

 

  • @는 id를 리소스(R.java)에서 정의하거나 참조한다라는 의미.
  •  + 는 ID를 새로정의한다는 의미이며, 처음 정의시만 사용하며, 참조할때는 붙이지 않는다.
  •  id는 소문자로 쓰며, 예약어임.
  • /뒤에 이름을 부여함.

 

XML 문서에 ID를 지정해 놓으면 이 이름이 R.java에 정수상수로 정의된다. (16진수 리소스구분을 위한 일련번호)

 

 

 

 layout_width, layout_height
  • match_parent(fill_parent) - 부모와 동일한 크기로. 여기는 부모는 activity_main. 화면크기 만큼
  • wrap_content - 안에 채워진 내용만큼
  • 상수크기 - 지정한 상수 크기 만큼.
    ( px(픽셀), in(인치), mm(밀리미터), pt(포인트), dp(밀도에 독립적단위),sp(폰트가변단위)

 

RelativeLayout 인 경우 객체의 위치관계가 중요하다. 어디 밑에 ..어디 위쪽에. 등등..

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText android:id="@+id/num1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:hint="첫번째수 입력"
        />
   
    <EditText android:id="@+id/num2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/num1"
        android:hint="두번째수 입력"
        />
    <Button android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/num2"
        android:text="두수합"
        />
   
    <Button android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/btn1"
        android:layout_below="@id/num2"
        android:text="지우기"
        />
    <EditText android:id="@+id/num3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn2"
        android:hint="연산 결과"
        />

</RelativeLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(2) MainActivity.java

; onClick메소드의 파라미터 View에 id정보가 들어있다.

   View의 자식으로 버튼, EditText 등이 존재한다. 이벤트가 발생한 객체를 얻어올수 있다. ( getId() )

 

package com.example.test02;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {
    EditText num1;
    EditText num2;
    EditText num3;
    Button btn1;
    Button btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // edittext의 참조값 얻어오기
        num1 = (EditText) findViewById(R.id.num1);
        num2 = (EditText) findViewById(R.id.num2);
        num3 = (EditText) findViewById(R.id.num3);
        // Button의 참조값 얻어오기.
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        // Button에 EventHandler 등록
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                int n1 = Integer.parseInt(num1.getText().toString());
                int n2 = Integer.parseInt(num2.getText().toString());
                int n3 = n1 + n2;
                // edittext에 값 넣기
                num3.setText("두 수의 합:" + n3);
                break;
            case R.id.btn2:
                num1.setText("");
                num2.setText("");
                num3.setText("");
                break;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

 

 

'Mobile > Android' 카테고리의 다른 글

#05 ( checkbox, radiobutton )  (0) 2013.01.29
#04( 입력한 값 보여주기 예제 )  (0) 2013.01.28
#02 ( 시작하기 )  (0) 2013.01.28
#01( Android Virtual Device Manager )  (0) 2013.01.28
#01( 설치하기 )  (0) 2013.01.28

간단한 예제 > Edittext에 값을 입력하고, 버튼을 클릭하면 하단에 보여주기.

 

- 버튼 이벤트 주기

- Toast

- layout/activity_main.xml

- layout에 추가한 resource에 대한 참조값 확인 : R.java

 

확인할 소스파일위치> 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(1) activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/edtName"
        android:text="Button" />

</RelativeLayout>

; EditText와  Button을 추가함.

; Graphical layout에서 추가해도 되나 직접 속성을 추가함. (속성을 이해하기 위해)

; 추가하면 Graphical layout 결과는 아래와 같다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(2) R.java

; 고치거나 추가할 것은 없다. 추가된 정보를 확인해 본다.

; 위에서 추가한 EditText나 Button의 참조대상 값이 보인다.

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.example.test01;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int ic_launcher=0x7f020000;
    }
    public static final class id {
        public static final int btn1=0x7f070001;
        public static final int edtName=0x7f070000;
        public static final int menu_settings=0x7f070002;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
    }
    public static final class menu {
        public static final int activity_main=0x7f060000;
    }
    public static final class string {
        public static final int app_name=0x7f040000;
        public static final int hello_world=0x7f040001;
        public static final int menu_settings=0x7f040002;
    }
    public static final class style {
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
   

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
       

        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.
   
 API 11 theme customizations can go here.

        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.
   
 API 14 theme customizations can go here.
         */
        public static final int AppBaseTheme=0x7f050000;
        /**  Application theme.
 All customizations that are NOT specific to a particular API-level can go here.
         */
        public static final int AppTheme=0x7f050001;
    }
}

 

(3) MainActivity.java

; OnClickListener 리스너 구현- onClick추상메소드 override하기.

; R.java에서 확인한 object에 대한 참조값 얻어오기.

   findViewById메소드를 이용해서 버튼,에디트텍스트의 참조값을 얻어온다. 해당 object타입으로 형변환해야 한다.

; 버튼에 이벤트 리스너를 등록한다.

; out.println을 사용할수 없어서 Toast라는 객체를 사용해 확인해 본다. 하단에 메시지박스같은 것이 Toast실행결과이다.

; 에뮬레이터 실행시킨 후 프로젝트 선택 --> run as --> 에뮬레이터로 넘어간다.

 

package com.example.test01;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    Button btn1;
    EditText edt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        //버튼에 대한 참조값 얻어오기.

        btn1 = (Button)findViewById(R.id.btn1);

 

        //에디트텍스트에 대한 참조값 얻어오기.
        edt1 = (EditText)findViewById(R.id.edtName);
       
        //버튼에 이벤트리스너 등록하기.

        btn1.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // 에디트텍스트에서 입력된 값 얻어오기.
        String msg = edt1.getText().toString();
       
        Toast.makeText(this, "input msg:" + msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

 

 

test 일력 후 Button 클릭하면 하단에 input msg:test (toast) 가 출력된다.

이제부터 시작이다.

'Mobile > Android' 카테고리의 다른 글

#05 ( checkbox, radiobutton )  (0) 2013.01.29
#04( 입력한 값 보여주기 예제 )  (0) 2013.01.28
#03( 합구하기 )  (0) 2013.01.28
#01( Android Virtual Device Manager )  (0) 2013.01.28
#01( 설치하기 )  (0) 2013.01.28

1. 이클립스

Window/Android Virtual Device Manager 실행.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2. 처음 실행시키면 아무것도 지정된것이 없다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

- New실행후 에뮬레이터 추가하기. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

- AVD Name : 임의로 지정.

   Device :  320 * 480 HVGA slider ( 개발에 맞게 설정 )

   Target : 4.1.2 버전으로. 4.2버전에서는 한글이 깨져서 나와서..

   CPU/ABL: ARM으로. 모바일은 ARM인가...

   나머지는 각자 맞게..

   OK.

 

- AVD1이 추가되었고, Start버튼도 활성화됨. Start시킴. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

띄는데 약간 시간이 걸린다.

 

 

'Mobile > Android' 카테고리의 다른 글

#05 ( checkbox, radiobutton )  (0) 2013.01.29
#04( 입력한 값 보여주기 예제 )  (0) 2013.01.28
#03( 합구하기 )  (0) 2013.01.28
#02 ( 시작하기 )  (0) 2013.01.28
#01( 설치하기 )  (0) 2013.01.28

+ Recent posts