Reputation: 648
I am trying to develop an Android application using fragments and I stumbled on a problem while trying to use Butterknife to binds views and use @OnClick annotation.
In my fragment I inflate different layouts depending on user's selection in menu. Lets say user selects settings so I then inflate my settings layout which holds button for logout. If user selects sync in menu I inflate my sync view which holds button to start sync.
My onCreateView looks something like the following code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
if(settings)
{
rootView = inflater.inflate(R.layout.settings_view, container, false);
} else {
rootView = inflater.inflate(R.layout.sync_view, container, false);
}
return rootView;
}
So then I created my @Onclick method for logout button
@OnClick(R.id.btnSettingsLogout)
public void logout() {
Toast.makeText(getActivity(), "Button was pressed!", Toast.LENGTH_SHORT).show();
}
and added ButterKnife.bind(this, rootView);
to the end of my onCreateView method befure I return rootView.
The problem is that now when I inflate my settings view everything works and I am greeted with toast message whenever I press my logout button but when I inflate my sync view application crashes because of the following exception:
java.lang.RuntimeException: Unable to bind views for si.vitez.testapp.DetailFragment
Is it possible to inject both views, so application won't crash no mater which of the two views will be inflated?
Upvotes: 2
Views: 1224
Reputation: 5220
you should use @Nullable
annotation for you method.
@Nullabale
@OnClick(R.id.yourId)
public void onClickMethod(){
// your code
}
see here for more information about this.
Upvotes: 3