java.lang.illegalStateException:黄油刀

java.lang.illegalStateException: Butterknife

我正在使用 butterknife 绑定我的视图,所以当 activity 启动时,会抛出以下异常

java.lang.RuntimeException: Unable to start activity ComponentInfo{..package name...}: java.lang.IllegalStateException: Required view 'l' with ID 2131558524 for field 'tabItem' and method 'check' was not found. If this view is optional add '@Nullable' (fields) or '@Optional' (methods) annotation.

注意:我在 setContentView(view) 之后调用了 Butterknife.bind(this) 并且这个视图不是可选的

我的代码

public class HandlingActivity extends AppCompatActivity {

@BindView(R.id.container_view)FrameLayout container;
@BindView(R.id.l)TabItem tabItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handling);
    ButterKnife.bind(this);
}

@OnClick(R.id.l)void check(){
    StoriesFragment storiesFragment = new StoriesFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.container_view,storiesFragment).commit();
     }
}

如果您的 TabItem 尚未准备好,则有可能,因此请在声明变量及其相应的 onclick 时尝试使用它。

参考自here

 @Nullable
 @BindView(R.id.l)TabItem tabItem;

 @Optional
 @OnClick(R.id.l)
  void check(){
     //method logic...
  }
  1. 检查你是否输入了build.gradle (module:app)

    dependencies {
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.jakewharton:butterknife:8.5.1'
    
    }
    
  2. 检查您的 ID 是否存在

  3. 尝试添加@OnClick(R.id.l)void check(View v){ ... }

在我的例子中,这个错误是因为我为不同的版本使用了两种布局:

  • activity_login.xml

  • activity_login.xml (v21)

我在 activity_login.xml 中添加了一个 progressBar 但是...

I forgot to added to activity_login.xml (v21).

在我的 Activity class:

中将注释 @Optional 添加到 @Onclick 后,它对我有用
@Optional
@OnClick({R.id.your_id_1, R.id.your_id_2})
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.your_id_1:
            break;
        case R.id.your_id_2:
            break;
    }
}

导入依赖项并绑定您的 Activity:

import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Optional;

public class YourActivity extends AppCompatActivity {

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

要在库中使用 Butter Knife,请将插件添加到您的构建脚本中:

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
  }
}

还有你的app/build.gradle

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'
    defaultConfig {
        applicationId 'your_app_id'
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

    }
}

dependencies {
        implementation 'com.jakewharton:butterknife:8.8.1'
        annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

干杯;]

我遇到了类似的错误,这是由于错误的布局文件在没有错误报告的相关字段的视图中膨胀。