HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

ButterKnife.bind with super class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withsuperbutterknifebindclass

Problem

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.

Solution

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

Code Snippets

public class BaseActivity {

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

}

Context

StackExchange Code Review Q#151463, answer score: 3

Revisions (0)

No revisions yet.