android - ButterKnife 使用不同布局在 fragment 中绑定(bind)

标签 android android-layout android-fragments butterknife

我正在尝试使用 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/

相关文章:

android - 如何隐藏/删除android中的标题栏

android - 获取自定义Listview Android中的总行数

android - 如何从另一个 fragment 打开一个新 fragment ?

java - 在 fragment 中使用 Google Places API 自动完成搜索栏

android - 使用bottomNavView时如何在 fragment 之间传递数据

android - 我的 trigger.io 应用程序的 'launchimage' 在 Galaxy Nexus 上太小

android - GoogleMaps.LocationServices NuGet 包说找不到命名空间

android - 应为 BEGIN_ARRAY 但在第 1 行第 96 列路径中为 BEGIN_OBJECT

android - getSurfaceTexture() 返回 null

java - OnCreate 方法中的 Android NullPointerException