DataBinding과 ViewBinding이 뭐가 다른가?
간단하게 말하자면, DataBinding은 이름처럼 데이터를 연결해주는 역할을 할수 있다. (데이터와 같이 결합해서 사용할 수 있음)
이론이 필요한 사람은 ViewBinding vs DataBinding 참고
android {
.
..
// 추가
buildFeatures{
dataBinding = true
}
}
<layout></layout>
전체를 감싼다.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/dataBindingTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="50sp" />
</LinearLayout>
</layout>
class MainActivity : AppCompatActivity() {
// 1. 추가
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 2. 추가
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// 예제 코드
binding.dataBindingTextView.text = "바뀐 텍스트"
}
}
<layout></layout>
으로 전체 레이아웃을 감싼다.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/fragmentText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment"
android:textSize="50sp" />
</FrameLayout>
</layout>
class TestFragment : Fragment() {
// 1. 추가
lateinit var binding: FragmentTestBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// 2. 추가
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_test, container, false)
// 예제
binding.fragmentText.text = "변경된 Fragment 텍스트"
// 3. 추가
return binding.root
}
}