1) gradle 추가
// 안드로이드 스튜디오 4.0 이상
android {
...
buildFeatures {
viewBinding = true
}
}
// 안드로이드 스튜디오 3.6 ~ 4.0
android {
...
viewBinding {
enabled true
}
}
2) MainActivity
// Java
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater()); // 1
setContentView(binding.getRoot()); // 2
}
private void updateUI(UserProfile userProfile){
binding.name.setText("아이유"); // 3
binding.phone.setText("010-1111-2222");
binding.address.setText("사랑시 고백구 행복동");
}
}
// kotlin
private lateinit var binding: ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.textView.text = "안녕"
}
}
// inflate: layout을 객체화 해줌
class BlankFragment : Fragment() {
private var _binding: FragmentBlankBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentBlankBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.textView.text = "안녕"
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
<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:viewBindingIgnore="true" // 뷰 바인딩 클래스 생성을 안하고 싶을 때
tools:context=".HelloActivity">
</androidx.constraintlayout.widget.ConstraintLayout>