java로 프로그램을 할 때 파라미터로 가장 많이 사용하게 되는 ObjectVO 객체이고 VO로 값을 받거나 전달해야 하는 경우 VO의 값을 확인 하려면 디버깅모드에서 Variables에 있는 값을 확인 하거나 Vo.getXxx()로 하나씩 출력을 해봐야 하는 불편함이 있는데 ObjectMapper를 이용하면 VoJSON 형태로 변환하여 사용할 수 있습니다.



 

먼제 pom.xml에 라이브러리를 등록 합니다.

 

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->

        <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>

            <artifactId>jackson-databind</artifactId>

            <version>2.11.0</version>

        </dependency>

 

main 으로 사용할 VO 파일을 생성 합니다.

 

public class SampleVo {

 

        private String username; /* 사용자ID*/

        private String name; /* 이름*/

        private Map<String, Object> mobile; /* 휴대전화*/

        private Map<String, Object> tel; /* 전화번호*/

       

        //getXxx, setXxx 생략

       

}

 

VO를 또 생성 합니다이건 Map<String, Object>로 설정한 mobile을 위한 Vo 입니다.


public class MovileVo {

 

        private String mobile1; /* 휴대전화1*/

        private String mobile2; /* 휴대전화2*/

        private String mobile3; /* 휴대전화3*/

       

        //getXxx, setXxx 생략

       

}

 

 

tel을 위한 Vo도 하나 더 추가 합니다.


public class TelVo {

 

        private String tel1; /* 전화번호1*/

        private String tel2; /* 전화번호2*/

        private String tel3; /* 전화번호3*/

       

        //getXxx, setXxx 생략

}

 

 

이제 Controller를 하나 만들고 코딩을 합니다.

MovileVo TelVo에 값을 설정하고 SampleVoMobileVoTelVo를 이용하여 값을 설정 합니다.



import com.fasterxml.jackson.databind.ObjectMapper;


        @RequestMapping(value = "/sample/test")

        public void sampleMethod(Model model) throws Exception {

              

               SampleVo sampleVo = new SampleVo();

               MovileVo movileVo = new MovileVo();

               TelVo telVo = new TelVo();

              

               movileVo.setMobile1("010");

               movileVo.setMobile2("1111");

               movileVo.setMobile3("2222");

              

               telVo.setTel1("02");

               telVo.setTel2("111");

               telVo.setTel3("2222");

              

               Map<String, Object> movileMap = new HashMap<String, Object>();

               Map<String, Object> telMap = new HashMap<String, Object>();

              

               movileMap.put("movile1", movileVo.getMobile1());

               movileMap.put("movile2", movileVo.getMobile2());

               movileMap.put("movile3", movileVo.getMobile3());

              

               telMap.put("tel1", telVo.getTel1());

               telMap.put("tel2", telVo.getTel2());

               telMap.put("tel3", telVo.getTel3());

              

               sampleVo.setUsername("copycoding");

               sampleVo.setName("카피코딩");

               sampleVo.setMobile(movileMap);

               sampleVo.setTel(telMap);

              

               ObjectMapper mapper = new ObjectMapper();

               String samString = mapper.writeValueAsString(sampleVo);

              

               System.out.println("=== sampleVo ===" + samString);

        }

 

ObjectMapper mapper = new ObjectMapper();

String samString = mapper.writeValueAsString(sampleVo);

ObjectMapper를 설정 하고 writeValueAsString()을 이용하면 JSON 형태의 String 값을 얻을 수 있습니다.

 

localhost:8080/sample/test를 호출하여 실행을 하여 log를 확인 해 봅니다.

 

=== sampleVo ==={"username":"copycoding","name":"카피코딩","tel":{"tel1":"02","tel2":"111","tel3":"2222"},"mobile":{"movile1":"010","movile3":"2222","movile2":"1111"}}

 

String형이라 다시 정리 하면

=== sampleVo ===

{

"username":"copycoding",

  "name":"카피코딩",

  "tel":{

        "tel1":"02",

        "tel2":"111",

        "tel3":"2222"

      },

  "mobile":{

        "movile1":"010",

        "movile3":"2222",

        "movile2":"1111"

      }

}

 

이런 결과를 볼 수 있습니다.


- copy coding -


Button.OnClickListener 객체를 생성하여 .버튼에 설정 해주는 방식입니다.

버튼 오브젝트를 생성하고

Button.OnClickListener btnObject = new View.OnClickListener(){public void onClick(View v){}};

이걸 callback으로 이용해서 버튼을 정의 합니다.

 

1. Layout에 이벤트 추가


activity_main.xmlButtonLayout을 구성 합니다.


<Button
android:id="@+id/btn_object1"
android:text="@string/btn_object1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />


3개의 버튼을 만들어서 테스트를 진행 합니다..

 

2. Activity에 기능 구현

 

Button.OnClickListener 객체를 생성 하고 각 버튼 클릭시 간단한 메시지를 보여주도록 합니다.


Button.OnClickListener btnObject = new View.OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.btn_object1) {
Toast.makeText(MainActivity.this, "Object Button1", Toast.LENGTH_SHORT).show();
} else if(v.getId() == R.id.btn_object2) {
Toast.makeText(MainActivity.this, "Object Button2", Toast.LENGTH_SHORT).show();
} else if(v.getId() == R.id.btn_object3) {
Toast.makeText(MainActivity.this, "Object Button3", Toast.LENGTH_SHORT).show();
}
}
};

onCreate()에서 버튼에 생성된 Button.OnClickListener 객체를 대입해 줍니다.


findViewById(R.id.btn_object1).setOnClickListener(btnObject);
findViewById(R.id.btn_object2).setOnClickListener(btnObject);
findViewById(R.id.btn_object3).setOnClickListener(btnObject);


3. 결과


버튼 3개가 구현되고 선택을 하면 해당 메시지가 나타납니다.


android button onclicklistener



4. Source Code

 

4.1 activity_main.xml


버튼 3개를 구현 합니다.


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_object1"
        android:text="@string/btn_object1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_object2"
        android:text="@string/btn_object2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_object3"
        android:text="@string/btn_object3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="260dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

4.2 strings.xml


button에 사용되는 text 내용 입니다.


<resources>
    <string name="app_name">Button Object</string>
    <string name="btn_object1">Object1</string>
    <string name="btn_object2">Object2</string>
    <string name="btn_object3">Object3</string>
</resources>


4.3 MainActivity.java


package copycoding.button.object.buttonobject;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

//    Button.OnClickListener btnObject = new View.OnClickListener(){public void onClick(View v){}};
    // 4. OnClickListener를 객체로 만드는 방법
    Button.OnClickListener btnObject = new View.OnClickListener() {
        public void onClick(View v) {
            if(v.getId() == R.id.btn_object1) {
                Toast.makeText(MainActivity.this, "Object Button1", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object2) {
                Toast.makeText(MainActivity.this, "Object Button2", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object3) {
                Toast.makeText(MainActivity.this, "Object Button3", Toast.LENGTH_SHORT).show();
            }
        }
    };

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

        // 4. OnClickListener를 객체로 만드는 방법
        findViewById(R.id.btn_object1).setOnClickListener(btnObject);
        findViewById(R.id.btn_object2).setOnClickListener(btnObject);
        findViewById(R.id.btn_object3).setOnClickListener(btnObject);
    }
}


다른 버튼 사용 관련 참조


[android] 안드로이드 버튼(1) onClick() 함수 사용 방법

[android] 안드로이드 버튼(2) 생성시 OnClickListener 구현 방법

[android] 안드로이드 버튼(3) OnClickListener 인터페이스 구현 방법

[android] 안드로이드 버튼(5) 버튼 생성 모음 이미지 버튼


- copy coding -


1

+ Recent posts