[Android SDK] Using butterknife for ActionBar Views

This is an example of how to inject your ActionBar Views and use them with Butterknife‘s @OnClick annotation:

ExampleActivity.java:

@OnClick(R.id.ab_detail_btn1)
 public void onBtn1Clicked(){
     Log.i(Constants.LOG_TAG, "AB Next clicked!");
 }
private void initActionBar() {
   ActionBar ab = getActionBar();
   ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(R.layout.ab_detail, null);
   ab.setCustomView(vg);
   ButterKnife.inject(this, vg);
   ab.setDisplayHomeAsUpEnabled(false);
   ab.setDisplayShowTitleEnabled(false);
   ab.setDisplayShowHomeEnabled(false);
   ab.setDisplayShowCustomEnabled(true);
 }
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  initActionBar();
}

ab_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
  <ImageButton
   android:id="@+id/ab_detail_btn1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />
</RelativeLayout>

With only a few code, without findViewById() calls, elegant, and maintainable 🙂

Let me know if it helps!

Have a nice day

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s