多个 ButterKnife activity

ButterKnife in multiple activity

这是我尝试与 ButterKnife 一起使用的代码,但是当我 运行 项目时出现以下错误。

错误:找不到符号 class Activity
错误:包 Activity 不存在
错误:包 Activity 不存在

基础Activity

public abstract class BaseActivity extends AppCompatActivity {

    private Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResource());
        ButterKnife.bind(this);

        setupUI();
    }


    protected abstract int getLayoutResource();

    protected abstract void setupUI();
}

主要Activity

public class MainActivity extends BaseActivity {

    @Override
    protected void setupUI() {

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }
}

注册Activity

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.editText_username)
    EditText et;

    @Override
    protected void setupUI() {


        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_register;
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}

为什么我不能将多个 Activity 与抽象绑定 class?

Github Project

首先,Activitybecause Unbinder is only needed for片段不需要Unbinder

其次,你最好用另一种方法覆盖,这样你就不需要设置onCreate。像这样:

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResource());
        ButterKnife.bind(this);

        setupUI();
    }

    protected abstract int getLayoutResource();

    protected abstract void setupUI();
}

然后你可以使用:

public class MainActivity extends BaseActivity {

    @Override
    protected void setupUI() {
      // setup the UI.
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }
}

这是将 ButterKnife 与抽象一起使用的工作示例 class:

https://github.com/isnotmenow/ButterKnifeAbstractSample