我有一个片段,我正在使用Butterknife。
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>
答案 0 :(得分:19)
InjectView
和inject
已替换为BindView
和bind
这是要遵循的步骤: -
将此添加到项目级build.gradle :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
将其添加到模块级build.gradle :
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
然后像这样使用Butterknife
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View calcView = inflater.inflate(R.layout.content_main, container, false);
unbinder = ButterKnife.bind(this, calcView);
return calcView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@OnClick(R.id.one)
public void one() {
Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
result.setText(result.getText().toString() + 1);
}
答案 1 :(得分:4)
只需使用此结构:
@OnClick(R.id.some_btn)
public void someButtonOnClick(View view) {
// do something
}
这里描述http://developer.android.com/reference/android/R.attr.html#onClick
答案 2 :(得分:3)
这对我有用:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.bind(getActivity(), view);
return view;
}
答案 3 :(得分:0)
如果您还有问题。清理项目并尝试运行。它应该修复。如果您仍有问题,请在someButtonOnClick()
中致电onCreate
并运行并将其删除,然后再次运行。它应该工作。它对我有用。