[Android] 뷰바인딩 (ViewBindnig)

선주·2022년 2월 11일
0

Android

목록 보기
5/11
post-thumbnail

📑 ViewBinding 적용 전의 소스코드

MainActivity.java

public class MainActivity extends AppCompatActivity {

	private TextView nameView, phoneView, addressView
    	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        nameView = findViewById(R.id.name);
        phoneView = findViewById(R.id.phone);
        addressView = findViewById(R.id.address);
        
        fetchUserProfile();
    }
    
    private void fetchUserProfile() {
    	UserProfile userProfile = new UserProfile();
        userProfile.name = "홍길동";
        userProfile.phone = "010-0000-0000";
        userProfile.address = "서울시 강남구 대치동";
        
        updateUI(userProfile);
    }
    
    private void updateUI(UserProfile userProfile) {
    	nameView.setText(userProfile.name);
        phoneView.setText(userProfile.phone);
        addressView.setText(userProfile.address);
    }
}

UserProfile.java

public class UserProfile {
	public String name;
	public String phone;
	public String address;
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

데이터를 화면에 표시하는 일반적인 절차

  • onCreate에서 id를 통해 뷰 객체를 가져와 nameView, phoneView, addressView 레퍼런스에 매칭한다. (뷰바인딩)
  • fetchUserProfile에서는 데이터를 로딩해온다.
  • updateUI에서는 가져온 데이터를 레퍼런스에 세팅한다. (데이터바인딩)



📚 ViewBinding (Java)

안드로이드 3.6버전 이상부터 사용할 수 있다.

build.gradle (module)

android {
	…
    viewBinding {
    	enabled true
    }
}

위 줄을 추가하고 Sync Now까지 완료하면 안드로이드 스튜디오가 클래스를 자동으로 만들어준다.

private TextView nameView, phoneView, addressView
    	
nameView = findViewById(R.id.name);
phoneView = findViewById(R.id.phone);
addressView = findViewById(R.id.address);
  • 이 클래스는 위의 과정을 대신해주는 역할을 한다.
  • res/layout 폴더 아래에 있는 모든 레이아웃 파일들에 대해서 모두 클래스가 생성된다.
  • 클래스명: 만약 레이아웃 이름이 activity_main.xml이라면 이 클래스의 이름은 ActivityMainBinding이 된다.
  • 클래스 위치: Android모드에서는 보이지 않고, Project모드로 바꿨을 때 볼 수 있다. app/build/generated/data_binding_base_class_source_out/debug/out/com/example/sample/databinding/ActivityMainBinding.java

이제 그럼 클래스를 사용해보자.

ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());

위의 코드 한 줄만으로 activity_main.xml 레이아웃 파일을 인플레이션해서 이 레이아웃의 id가 정의되어 있는 뷰들을 레퍼런스로 만들고 레퍼런스에 실체 객체를 매칭해주는 일이 수행된다.


// ViewBinding 사용 전
setContentView(R.layout.activity_main);

// ViewBinding 사용 후
setContentView(binding.getRoot());

binding 객체에는 인플레이션된 객체의 최상위 객체를 가져오는 getRoot 메서드가 존재한다. 따라서 setContentView에도 리소스아이디를 전달하는 대신에 이미 생성이 된 루트뷰를 전달해줄 수 있다.


// ViewBinding 사용 전
private void updateUI(UserProfile userProfile) {
    nameView.setText(userProfile.name);
    phoneView.setText(userProfile.phone);
    addressView.setText(userProfile.address);
}

// ViewBinding 사용 후
private void updateUI(UserProfile useProfile) {
	binding.name.setText(userProfile.name);
    binding.phone.setText(userProfile.phone);
    binding.address.setText(userProfile.address);
}

updateUI도 역시 이렇게 바꿔줄 수 있다.




ViewBinding을 활용한 MainActivity.java의 전체 코드

public class MainActivity extends AppCompatActivity {

	private ActivityMainBinding binding;
    	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        binding = ActivityMinBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        fetchUserProfile();
    }
    
    private void fetchUserProfile() {
    	UserProfile userProfile = new UserProfile();
        userProfile.name = "홍길동";
        userProfile.phone = "010-0000-0000";
        userProfile.address = "서울시 강남구 대치동";
        
        updateUI(userProfile);
    }
    
    private void updateUI(UserProfile useProfile) {
		binding.name.setText(userProfile.name);
    	binding.phone.setText(userProfile.phone);
    	binding.address.setText(userProfile.address);
	}
}

뷰바인딩을 위한 코드가 메인액티비티 소스코드에서 사라졌기 때문에 소스코드가 보다 간결해진 모습이다. 다음 포스팅 내용인 데이터바인딩까지 활용해 updateUI 코드도 단축하면 메인액티비티에서는 실제 중요한 로직인 fetchUserProfile에 집중할 수 있게 된다.




📚 ViewBinding (Kotlin)

build.gradle (modlue)

android {
	…
    buildFeatures {
    	viewBinding true
    }
}

위 줄을 추가하고 Sync Now까지 완료하면 안드로이드 스튜디오가 클래스를 자동으로 만들어준다.


MainActivity.kt

class MainActivity : AppCompatActivity() {
	lateinit var binding : ActivityMainBinding;
    
    override fun onCreate(savedInstanceState: Bundle?) {
    	super.onCreate(savedInstanceState)
        
    	binding = ActivityMainBinding.inflate(layoutInflater);
        setContentView(binding.root)
        binding.textView.text = "안녕하세요.";
    }    
}

뷰바인딩 변수 binding은 onCreate에서 초기화를 하기 위해 lateinit로 지정한다. Java에서 root객체에 getRoot 메서드로 접근했던 것과 달리, Kotlin에서는 바로 root에 접근한다.

profile
기록하는 개발자 👀

0개의 댓글