일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- SPI
- Kotlin
- 쌓기게임
- AfxMessageBox
- math
- android
- WebView
- synergy
- 동적프로그래밍
- 제곱근
- DataStructure
- 형변환
- DynamicProgramming
- Dokka
- devicedriver
- 보늬밤
- memory
- 코인거스름돈
- 피보나치
- LRU
- Java
- Dialog
- darkmode
- 리틀포레스트
- MFC
- stack
- QoS
- FirebaseAuth
- 피요모리2
- Collection
- Today
- Total
퉁탕퉁탕 만들어보자
View Binding 본문
멀고먼 안드로이드 마을
View binding도 data binding도 없던 옛날에는 findViewById() 라는 함수를 쓰는것 밖에 방법이 없었습니다.
그러면 안타깝게도 null pointer exception이 나기도 했었고, Type을 실수로 잘못 넣어주면 exception이 나며 죽기도 했습니다.
(중간에 나왔다가 사라진 kotlin extension도 있었습니다)
이젠 viewBinding으로 layout xml 파일과 java(kotlin) 파일을 연결하는게 대세가 되었습니다.
(jetpack compose때문에 다시 역사의 뒤안길로 사라질지도 모름)
사용하는 방법은 build.gradle 파일에 android 블럭에 아래와 같이 viewBinding을 쓴다고 써줍니다.
android {
//...
viewBinding {
enabled = true
}
}
그러면 내 MainActivity에서 다음과 같이 xml 파일에 넣어둔 view들을 사용할 수 있습니다.
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View root = binding.getRoot();
setContentView(root);
binding.errorText.setText("something wrong");
...
}
}
1) xml파일 이름으로 class가 생성됩니다. ActivityMainBinding (activity_main.xml)
2) Layout inflater로 inflate해준 return value 로 binding 객체를 초기화 해줍니다,
3) 그리고 binding.getRoot()로 root를 얻어서 setContentView() 해줍니다.
4) 이제 binding 에서 내가 xml에 선언한 뷰를 id로 얻어와서 맘껏 사용합니다.
<TextView
android:id="@+id/error_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center"/>
ActivityMainBinding.java 파일은 app/build/generated/data_binding_class_source_out/debug/out/com/XXX/앱이름/databinding/ 밑에 존재합니다.
public final class ActivityMainBinding implements ViewBinding {
@NonNull
private final LinearLayout rootView;
@NonNull
public final TextView errorText;
private ActivityMainBinding(@NonNull LinearLayout rootView, @NonNull TextView errorText) {
this.rootView = rootView;
this.errorText = errorText;
}
@Override
@NonNull
public LinearLayout getRoot() {
return rootView;
}
@NonNull
public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_main, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ActivityMainBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.error_text;
TextView errorText = ViewBindings.findChildViewById(rootView, id);
if (errorText == null) {
break missingId;
}
return new ActivityMainBinding((LinearLayout) rootView, errorText);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
내 layout xml 파일에 만들어둔 친구들이 camelCase로 변경되어서 member변수로 선언되어있고, findChildViewById를 통해서 값을 넣어서 생성해주고 있는것이 보입니다.
그러면 jetpack compose의 시대가 올때까지 view binding을 잘 사용하면서 편리한 코딩을 하시길 바랍니다~!
'Computer > Android' 카테고리의 다른 글
Android broadcast 수신 (0) | 2022.05.09 |
---|---|
Android Webview Javascript interface (2) | 2022.05.08 |
Android Rendering? (0) | 2022.05.08 |
Android View LifeCycle (0) | 2022.05.07 |
Android RecyclerView (0) | 2022.05.05 |