【问题标题】:ButterKnife Bind in Fragment using different layoutsButterKnife Bind in Fragment 使用不同的布局
【发布时间】:2016-01-27 10:25:56
【问题描述】:

我正在尝试使用 Fragment 开发 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();
    }

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

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

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

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

【问题讨论】:

    标签: android android-layout android-fragments butterknife


    【解决方案1】:

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

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

    请参阅here 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多