[ButterKnife 목차]
====================================
1. ButterKnife의 특징
2. 사용법1) Gradle 파일 설정
2) ButterKnife 라이브러리 bind
2) ButterKnife 라이브러리 bind
3. 기능1) View를 담을 변수를 선언
2) View Lists
3) Listener Binding (onClickListener)
4) Resource Binding
5) Non-Activity Binding
6) Binding Reset
7) Adapter
8) Multi-Method Listeners
9) Optional Bindings
10) ETC
3) Listener Binding (onClickListener)
4) Resource Binding
5) Non-Activity Binding
6) Binding Reset
7) Adapter
8) Multi-Method Listeners
9) Optional Bindings
10) ETC
4. License
====================================
1. ButterKnife의 특징
1) 필드나 메소드를 안드로이드 뷰에 어노테이션(@)을 이용하여 편하게 접근할 수 있도록 도와주는 안드로이드 라이브러리
=> ButterKnife 공식 홈페이지 https://github.com/JakeWharton/butterknife
2) 다수의 안드로이드 개발자들과 협업할때 View, Resource를 바인딩 하는 convention을 제공
=> 코드의 가독성 및 View ID 검색 및 효율성을 높여주는데 참 좋은것 같음
※ 자바 어노테이션(Annotation, @)이란?
2. 사용법
1) Gradle 파일 설정
build.gradle 파일을 열어 dependencies를 추가해주시면 라이브러리 추가
dependencies { compile 'com.jakewharton:butterknife:7.0.1'} |
2) ButterKnife 라이브러리 bind
onCreate메서드에서 setContentView(LayoutID);를 한 후에, 바인드를 해주어야 함
Butternife.bind(this); |
3. 기능
1) View를 담을 변수를 선언
이때까지 귀찮게, findViewById(viewID)를 하는 것을 내부적으로 ButterKnife가 도와주게 됨
@Bind(R.id.tv_info) TextView tv_info; @Bind(R.id.btn_method) Button btn_method; @Bind(R.id.btn_listener) Button btn_listener; @Bind(R.id.btn_implements) Button btn_implements; |
class ExampleActivity extends Activity { @BindView(R.id.title) TextView title; @BindView(R.id.subtitle) TextView subtitle; @BindView(R.id.footer) TextView footer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); // TODO Use fields... } } |
2) View Lists
여러 View를 (예제에서는 EditText) List로 관리하는 예제입니다. View들을 List에 담아 놓고 ButterKnife.apply()함수로 속성값을 일괄 적용하는 모습을 보여주고 있는데요 DISABLE, ENABLED와 같은 interface가 어떻게 되어 있는지 구현부 까지 보여주고 있습니다.
// You can group multiple views into a List or array. @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews; // The apply method allows you to act on all the views in a list at once. ButterKnife.apply(nameViews, DISABLE); ButterKnife.apply(nameViews, ENABLED, false); // Action and Setter interfaces allow specifying simple behavior. static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() { @Override public void apply(View view, int index) { view.setEnabled(false); } }; static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() { @Override public void set(View view, Boolean value, int index) { view.setEnabled(value); } }; // An Android Property can also be used with the apply method. ButterKnife.apply(nameViews, View.ALPHA, 0.0f); |
3) Listener Binding (onClickListener)
@OnClick(R.id.btn_method) void methodButtonClick() { } @OnClick(R.id.btn_listener) void listenerButtonClick() { } @OnClick(R.id.btn_implements) void implementsButtonClick() { } |
@OnClick({R.id.btn_method, R.id.btn_listener, R.id.btn_implements}) void buttonEvents(View v) { //이벤트를 처리할 로직... } |
4) Resource Binding
Bind pre-defined resources with @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString, which binds an R.bool ID (or your specified type) to its corresponding field.
class ExampleActivity extends Activity { @BindString(R.string.title) String title; @BindDrawable(R.drawable.graphic) Drawable graphic; @BindColor(R.color.red) int red; // int or ColorStateList field @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field // ... } |
5) Non-Activity Binding
You can also perform binding on arbitrary objects by supplying your own view root.
public class FancyFragment extends Fragment { @BindView(R.id.button1) Button button1; @BindView(R.id.button2) Button button2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container, false); ButterKnife.bind(this, view); // TODO Use fields... return view; } } |
6) Binding Reset
Fragments have a different view lifecycle than activities. When binding a fragment in onCreateView, set the views to null in onDestroyView. Butter Knife returns an Unbinder instance when you call bind to do this for you. Call its unbind method in the appropriate lifecycle callback
public class FancyFragment extends Fragment { @BindView(R.id.button1) Button button1; @BindView(R.id.button2) Button button2; private Unbinder unbinder; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container, false); unbinder = ButterKnife.bind(this, view); // TODO Use fields... return view; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } } |
7) Adapter
Another use is simplifying the view holder pattern inside of a list adapter
public class MyAdapter extends BaseAdapter { @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; if (view != null) { holder = (ViewHolder) view.getTag(); } else { view = inflater.inflate(R.layout.whatever, parent, false); holder = new ViewHolder(view); view.setTag(holder); } holder.name.setText("John Doe"); // etc... return view; } static class ViewHolder { @BindView(R.id.title) TextView name; @BindView(R.id.job_title) TextView jobTitle; public ViewHolder(View view) { ButterKnife.bind(this, view); } } } |
8) Multi-Method Listeners
Method annotations whose corresponding listener has multiple callbacks can be used to bind to any one of them. Each annotation has a default callback that it binds to. Specify an alternate using the callback parameter.
@OnItemSelected(R.id.list_view) void onItemSelected(int position) { // TODO ... } @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED) void onNothingSelected() { // TODO ... } |
9) Optional Bindings
@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere; @Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() { // TODO ... } |
10) ETC
Also included are findById methods which simplify code that still has to find views on a View, Activity, or Dialog. It uses generics to infer the return type and automatically performs the cast.
View view = LayoutInflater.from(context).inflate(R.layout.thing, null); TextView firstName = ButterKnife.findById(view, R.id.first_name); TextView lastName = ButterKnife.findById(view, R.id.last_name); ImageView photo = ButterKnife.findById(view, R.id.photo); |
Add a static import for ButterKnife.findById and enjoy even more fun.
4. License
Copyright 2013 Jake Wharton
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
출처 : 인터넷에서 RxAndroid 검색하여 필요한 정보를 다양한 사이트에서 종합하여 작성된 것입니다. 많은 사이트 내용을 종합하여 공부하여 작성하다보니 일일이 나열하지 못하였습니다. ㅈㅅ(_ _) 이글은 자유롭게 퍼 가셔서 도움이 되었으면 좋겠습니다. 감사합니다.
댓글 없음:
댓글 쓰기