ButterKnife Bind in Fragment 使用不同的布局

ButterKnife Bind in Fragment using different layouts

我正在尝试使用片段开发一个 Android 应用程序,但在尝试使用 Butterknife 绑定视图和使用 @OnClick 注释时偶然发现了一个问题。

在我的片段中,我根据用户在菜单中的选择展开不同的布局。假设用户选择设置,然后我会膨胀我的设置布局,其中包含用于注销的按钮。如果用户在菜单中选择同步,我会膨胀我的同步视图,其中包含开始同步的按钮。

我的 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();
    }

并在 return rootView 之前将 ButterKnife.bind(this, rootView); 添加到我的 onCreateView 方法的末尾。

问题是,现在当我膨胀我的设置视图时,一切正常,每当我按下注销按钮时,我都会收到 toast 消息,但是当我膨胀我的同步视图应用程序时,由于以下异常而崩溃:

java.lang.RuntimeException: Unable to bind views for si.vitez.testapp.DetailFragment

是否可以同时注入两个视图,这样无论两个视图中的哪一个被膨胀,应用程序都不会崩溃?

你应该为你的方法使用 @Nullable 注释。

@Nullabale
@OnClick(R.id.yourId)
public void onClickMethod(){
 // your code
}

有关此内容的更多信息,请参阅 here