Android - 自定义 View 可以通过不指定 ID 来绑定(bind)到自己的监听器 - 不起作用

标签 android butterknife

我关注butterknife instruction正如他们所说:“自定义 View 可以通过不指定 ID 来绑定(bind)到它们自己的监听器。”

等级

Gradle 
compile 'com.jakewharton:butterknife:7.0.0'

我创建一个 BaseButton:

public class BaseButton extends Button {

public BaseButton(Context context) {
    super(context);
}

public BaseButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@OnClick
public void onClick() {
    System.out.println("Hello");
}}

Activity 主

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<com.example.BaseButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="test"/>

和MainActivity

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
}

//    @OnClick(R.id.button)
//    public void buttonPressed(){
//        System.out.println("buttonPressed");
//    }
}

如果我取消注释buttonPressed方法,则会显示“buttonPressed”。当我发表评论时,什么也没有发生。我期望的是先看到“hello”,然后看到“buttonPressed”。

你有什么想法吗?谢谢。

最佳答案

这里有两个问题:

  1. View 永远不会调用 ButterKnife.bind(this) 将点击监听器绑定(bind)到自身。如果没有这个,就无法知道何时附加监听器。您的 Activity 中的调用不会隐式地将 View 绑定(bind)到其自身。
  2. 如果您在 Activity 中为按钮添加了 @OnClick ,并且为按钮在其内部添加了 @OnClick,其中之一是将覆盖另一个。 Butter Knife 只是创建一个点击监听器并在 View 上调用 setOnClickListener 。由于您有两个,因此一个将简单地替换另一个,并且您将不再看到第一个调用 bind 的日志行。

关于Android - 自定义 View 可以通过不指定 ID 来绑定(bind)到自己的监听器 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31112075/

相关文章:

android - 我不(知道)使用 ro.serialno,但应用程序因此而崩溃

Android Wear 模拟器显示 Google Play 服务错误 SERVICE_VERSION_UPDATE_REQUIRED

android - 将 butterknife 添加到 android 库项目会为库类提供编译时错误 "package does not exists"

android - Android 中的 Fragment 回调与 EventBus

android - HttpClient获取新域名后产生SSLException

android google play 服务过时了

android - 使用 Butter Knife 实现事件 Spinner

java - 如何在 RecyclerView 适配器中用 ViewBinding 替换 ButterKnife

java - onClickListener 使用 Butterknife

android - Proguard 重复 Zip 条目