4
\$\begingroup\$

I am using ButterKnife in my project, and as we know we have to write ButterKnife.bind(this); in all the activities, so I have just created BaseActivity like this:

public class BaseActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState, int layout) {
        super.onCreate(savedInstanceState);
        setContentView(layout);
        ButterKnife.bind(this);
    }
}

and I am calling it from other activity like this

public class SplashActivity extends BaseActivity {

    @BindView(R.id.txtName)
    TextView txtName;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_splash);
    }
}

I want to know whether it is good practice to follow this approach.

\$\endgroup\$
3
\$\begingroup\$

Override setContentView instead of a different onCreate that receives the layout id.

public class BaseActivity {

    protected void setContentView(Int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
    }

}

Overriding this makes it more consistent (no custom onCreate) with the android style, I think.

I dont see any problem of using it, its cool since everytime you create a new activity its already there so just add @BindView and it works.

Other alternative is not using ButterKnife but Kotlin and Kotlin Extensions, take a look.

https://kotlinlang.org/docs/tutorials/android-plugin.html

\$\endgroup\$
2
  • \$\begingroup\$ I have created BaseActivity for many purposes, but i just want to know whether its good practice to write ButterKnife,bind() in BaseActivity, so that i can omit writing that line in all other activities \$\endgroup\$ Jan 4 '17 at 12:59
  • 1
    \$\begingroup\$ @RaviRupareliya check the updated answer \$\endgroup\$ Jan 4 '17 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.