repositories { maven { url 'https://dl.bintray.com/alexeydanilov/maven' } } dependencies { compile 'com.danikula:aibolit:1.0' }
public class AibolitChatActivity extends Activity { // annotate fields to be injected... @InjectView(R.id.messageEditText) private EditText messageEditText; @InjectView(R.id.historyListView) private ListView historyListView; @InjectResource(R.string.symbols_count) private String symbolsCountPattern; @InjectSystemService(Context.NOTIFICATION_SERVICE) private NotificationManager notificationManager; @InjectService private HttpManager httpManager; @InjectResource(R.layout.content) private View content; ... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_activity); // initialize annotated fields and methods Aibolit.doInjections(this); // or just Aibolit.setInjectedContentView(this); ... } // annotate event handlers... @InjectOnClickListener(R.id.sendButton) private void onSendButtonClick(View v) { // handle onClick event } @InjectOnClickListener(R.id.clearHistoryButton) private void onClearHistoryButtonClick(View v) { // handle onClick event } @InjectOnTextChangedListener(R.id.messageEditText) public void onMessageTextChanged(CharSequence s, int start, int before, int count) { // handle text changed event } ... }
Aibolit.doInjections(this);
method Aibolit.doInjections(this);
after you set the content to activate. setContentView(layoutId); Aibolit.doInjections(this);
Aibolit.setInjectedContentView(this);
@InjectService private HttpManager httpManager;
class ViewInjector extends AbstractFieldInjector<InjectView> { @Override public void doInjection(Object fieldOwner, InjectionContext injectionContext, Field field, InjectView annotation) { int viewId = annotation.value(); View view = injectionContext.getRootView().findViewById(viewId); if (view == null) { // throw exception... } if (!field.getType().isAssignableFrom(view.getClass())) { // throw exception... } try { field.setAccessible(true); field.set(fieldOwner, view); } catch (IllegalArgumentException e) { // throw exception... } catch (IllegalAccessException e) { // throw exception... } } }
Source: https://habr.com/ru/post/132126/
All Articles