【发布时间】:2014-07-30 08:02:24
【问题描述】:
我有一个正在使用 Butterknife 的 Fragment。
public class FooFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.foo, container, false);
ButterKnife.inject(this, view);
return view;
}
@OnClick(R.id.some_btn)
public void someButtonOnClick() {
// do something
}
}
但是,当点击屏幕上的按钮时,永远不会调用 someButtonOnClick 方法。
对我在 Butterknife 框架中做错了什么的想法?
这是正在使用的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/White">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/some_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="@dimen/xsmall_margin"
android:background="@drawable/some_btn_selection" />
<Button
android:id="@+id/some_other_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="@dimen/xsmall_margin"
android:background="@drawable/some_other_btn_selection" />
</LinearLayout>
</LinearLayout>
【问题讨论】:
-
可能不相关(因为它会导致编译错误),但是您是否有机会尝试在库项目中执行此操作(与普通的 android 应用程序项目相比)? ButterKnife flat-out 在图书馆项目中不起作用,因为他们的 R.id 不是最终的。第二个问题,您是否将此片段子类化并期望它起作用?我觉得 ButterKnife 注释(如 OttoBus)仅在被实例化的实际类上有效。如果您要对此片段进行子类化,请尝试在子类中重新实现 someButtonOnClick 方法(带有注释)以确认问题。
-
给我看 R.layout.foo
-
不,它不是库的一部分,我的 Fragment 类也不是 Fragment 以外的任何类的子类。
-
我还尝试在 Activity 的 onCreate 中放置一个 ButterKnife.inject(this),认为 ButterKnife 需要它来包含 Activity,但很可惜,没有乐趣。我仍然无法让它为 Fragments 工作,只是 Activity。
-
你得到什么解决方案,我也面临同样的问题
标签: android fragment butterknife