我正在尝试使用 fragment 开发 Android 应用程序,在尝试使用 Butterknife 绑定(bind) View 并使用 @OnClick 注释时偶然发现了一个问题。
在我的 fragment 中,我根据用户在菜单中的选择来扩展不同的布局。假设用户选择设置,然后我会膨胀我的设置布局,其中包含用于注销的按钮。如果用户在菜单中选择同步,我会膨胀我的同步 View ,其中包含开始同步的按钮。
我的 onCreateView 看起来类似于以下代码:
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;
}
然后我为注销按钮创建了 @Onclick 方法
@OnClick(R.id.btnSettingsLogout)
public void logout() {
Toast.makeText(getActivity(), "Button was pressed!", Toast.LENGTH_SHORT).show();
}
并在返回 rootView 之前将 ButterKnife.bind(this, rootView);
添加到 onCreateView 方法的末尾。
问题是,现在当我膨胀我的设置 View 时,一切正常,每当我按下注销按钮时,我都会收到 toast 消息,但当我膨胀我的同步 View 应用程序时,由于以下异常而崩溃:
java.lang.RuntimeException: Unable to bind views for si.vitez.testapp.DetailFragment
是否可以注入(inject)两个 View ,这样无论两个 View 中的哪个 View 膨胀,应用程序都不会崩溃?
最佳答案
您应该为您的方法使用@Nullable
注释。
@Nullabale
@OnClick(R.id.yourId)
public void onClickMethod(){
// your code
}
参见here了解更多相关信息。
关于android - ButterKnife 使用不同布局在 fragment 中绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034718/