본문 바로가기

안드로이드

안드로이드_데이터 바인딩

데이터바인딩(DataBinding)

  • 특징

    • XML 파일에 Data를 연결하여 사용할 수 있게 도와주는 Android JetPack 라이브러리의 기능 중 하나

    • 불필요한 코드(글루 코드, ex. findViewById())의 사용 최소화

  • 구현

    1. DataBinding 적용 전 코드

      • activity_main.xml

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        <?xml version="1.0" encoding="utf-8"?>
        <androidx.constraintlayout.widget.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">
         
            <TextView
                android:id="@+id/textView"
                 ... 생략 ...
                />
         
            <Button
                android:id="@+id/btn_change"
                 ... 생략 ...
                />
         
        </androidx.constraintlayout.widget.ConstraintLayout>
        cs
      • MainActivity.java

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        package com.example.databinding;
         
        import androidx.appcompat.app.AppCompatActivity;
         
        import //...생략
         
        public class MainActivity extends AppCompatActivity {
            Button ChangeBtn;
            TextView textView;
            int num;
            String str;
         
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //---- layout 설정
                setContentView(R.layout.activity_main);
         
                //---- XML 파일의 TextView, Button 받아오기
                textView = findViewById(R.id.textView);
                ChangeBtn = findViewById(R.id.btn_change);
         
                //---- 클릭 이벤트 설정(클릭 시 textView 숫자 ++)
                ChangeBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        num = Integer.parseInt((String)textView.getText());
                        str = Integer.toString(num+1);
                        textView.setText(str);
                    }
                });
            }
        }
        cs
    2. DataBinding 적용

      • build.gradle(app)에 dataBinding 추가 후 SyncNow

        1
        2
        3
        4
        5
        6
        7
        8
        9
        android {
            ... 생략 ...
            
            dataBinding {
                enable true
            }
            
            ... 생략 ...
        }
        cs
      • 원래의 activity_main.xml을 <layout> 태그로 감싸고 <data> 추가

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        <?xml version="1.0" encoding="utf-8"?>
        <layout 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">
         
            <!-- 추가 -->
            <data>
                <variable
                    name="main"
                    type="com.example.databinding.MainActivity"/>
            </data>
            
            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">
                <!-- 아래 항목은 위(<layout> 태그)와 중복되므로 삭제-->
                <!-- 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"-->
                
                ... 생략 ...
            
            </androidx.constraintlayout.widget.ConstraintLayout>
        </layout>
        cs
      • MainActivity.java 수정

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        package com.example.databinding;
         
        import //...생략
         
        import com.example.databinding.databinding.ActivityMainBinding;
         
        public class MainActivity extends AppCompatActivity {
            int num;
            String str;
         
        //++++ 수정 1) Binding 객체 생성
            ActivityMainBinding binding;
         
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
        //++++ 수정 2) layout 설정
                binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
         
                //---- 클릭 이벤트 설정(클릭 시 textView 숫자 ++)
                binding.btnChange.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
        //++++ 수정 3) 생성한 binding 객체로 XML 파일 내의 View에 접근
                        num = Integer.parseInt((String)binding.textView.getText());
                        str = Integer.toString(num+1);
                        binding.textView.setText(str);
                    }
                });
            }
        }
        cs

+ Recycling View에 DataBinding 적용

  • 구현

    1. build.gradle(app) 수정

      1
      2
      3
      4
      5
      6
      7
      android {
          ... 생략
          dataBinding {
              enable true
          }
          ... 생략
      }
      cs
    2. activity_main.xml 수정

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      <?xml version="1.0" encoding="utf-8"?>
      <layout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
       
          <data>
              <variable
                  name="main"
                  type="com.example.recycler.MainActivity" />
          </data>
       
          <!-- ConstraintLayout 태그 부분 -->
       
      </layout>
      cs
    3. MainActivity.java 수정

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      // ...생략
      import com.example.recycler.databinding.ActivityMainBinding;
      // ...생략
       
      public class MainActivity extends AppCompatActivity {
          //++++ Binding 객체 추가
          ActivityMainBinding binding;
          InfoAdapter adapter;
       
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
       
              //++++ Layout 설정
              binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
       
              // ==생략 == (ArrayList에 데이터 추가)
       
              //++++ RecyclerView에 LayoutManager 지정
              binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
       
              //++++ RecyclerView에 Adapter 지정
              adapter = new InfoAdapter(list);
              binding.recyclerView.setAdapter(adapter);
          }
      }
      cs
    4. item_info.xml 수정

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      <?xml version="1.0" encoding="utf-8"?>
      <layout xmlns:android="http://schemas.android.com/apk/res/android">
       
          <data>
              <variable
                  name="movie"
                  type="com.example.recycler.Info"/>
       
          </data>
          
          <!-- FrameLayout 태그 부분 -->
          
      </layout>
      cs
    5. InfoAdapter.java 수정

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      // ... 생략
      import com.example.recycler.databinding.ItemInfoBinding;
      // ... 생략
       
      public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
          //---- 데이터가 저장될 배열
          private ArrayList<Info> data = null;
       
          //---- 초기화
          InfoAdapter(ArrayList<Info> list) {
              data = list;
          }
       
          //---- 아이템 뷰를 저장하고 화면에 보여주는 ViewHolder 클래스 생성
          static class ViewHolder extends RecyclerView.ViewHolder {
              //++++ Binding 객체
              ItemInfoBinding binding;
       
              //++++ 생성자의 인자를 Binding 객체로 수정
              ViewHolder(ItemInfoBinding binding) {
                  super(binding.getRoot());
                  this.binding = binding;
              }
       
              //++++ 데이터 넣는 함수 분리하여 구현
              public void bind(Info info) {
                  binding.tvName.setText(info.getName());
                  binding.tvAge.setText(info.getAge());
              }
          }
       
          //---- ViewHolder 생성
          @NonNull
          @Override
          public InfoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
              //++++ 인플레이션
              ItemInfoBinding binding = ItemInfoBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
       
              return new ViewHolder(binding);
          }
       
          //++++ 데이터를 bind()에 전달
          @Override
          public void onBindViewHolder(@NonNull InfoAdapter.ViewHolder holder, int position) {
              Info info = data.get(position);
              holder.bind(info);
          }
       
          //---- 전체 데이터 수 리턴
          @Override
          public int getItemCount() {
              return data.size();
          }
      }
      cs