Reputation: 666
I have 3 activities with the same toolbar. I would like to avoid copying code on each activity. I know I can use <include>
tags in every layout in order to reuse the same layout for the toolbar. Now I would like to share the event handlers for each button of the toolbar in all the activities. I am thinking of making a toolbarActivity
which extends Activity
class and the 3 activities extends toolbarActivity
, so in onCreate method, when I call base.OnCreate
, all the event handlers would be defined. But, SetContentLayout
was not called yet, so base.OnCreate
will not find the buttons. Remember the 3 activities have different layouts. Do you know the best way to reuse code in order to avoid copying all the event handlers in OnCreate method for every activity and allowing me to override some functionality?
Upvotes: 2
Views: 765
Reputation: 696
Android is used on mobile devices so at development time their is no way to know the size and dimensions of the users device. On large devices many UI elements can fit. On smaller devices few UI elements can fit. Your question relates to this dilemma and therefore has many possible answers. Logically for code to work it must exist inside the source, ie you could cut and paste, a bad solution because you end up with many versions of this "same" toolbar or you could refer/reference one "external" toolbar. Fragments come to mind as does having a separate source file. UI source files can be thought of as pairs. Java for dynamic elements and xml for static. So in summary just reference an external fragment that has implemented your toolbar.
Upvotes: 2
Reputation: 4076
You could define a base activity which all your other activities extend, and make it implement a click listener (or whatever interface you are using to listen for button presses). You can check the Id of the clicked view and thus provide a callback to perform whatever logic you want.
public class BaseActivity extends Activity implements OnClickListener {
public void onCreate() {
myBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (R.id.my_btn == v.getId()) {
onFoo();
}
}
protected void onFoo() {
// TODO handle foo
}
}
You can then override the method in your subclasses if you need to provide different behaviour.
public class DifferentActivity extends BaseActivity {
@Override protected void onFoo() {
super.onFoo()
// TODO handle foo differently
}
}
Upvotes: 1
Reputation: 5415
If you keep the naming conventions for the buttons and other things in each layout that are tied to the references in your activities then you should have no problem.
For example if you have a '@+id/login_button' in one layout then just use the same convention for the same type of button in the next one and youll be fine.
Upvotes: 1