保持Java中的BaseActivity与Kotlin Activity兼容

我想知道是否有办法维护一个BaseActivity(Java),例如,具有Java和Kotlin活动功能的BottomNavigationView。 将来我打算把(几个)Java活动变成Kotlin,因为新的活动是在Kotlin开发的。 问题在于Java能够保持BottomNavigationView正确创建,因为Kotlin扮演的是null,而BottomNavigationView是在Java环境中维护的循环之后加载的。 另一个尝试是尝试将我的Java BaseActivity转换成Kotlin,但打破了各种Java活动的操作。

class KotlinActivity : BaseActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my_wishes_list) ButterKnife.bind(this) //bottomNavigationMenu is null and lost all configurations from the BaseActivity bottomNavigationMenu.menu.getItem(0).isChecked = true } } public class BaseActivity extends AppCompatActivity { @BindView(R.id.bottom_navigation_menu) protected BottomNavigationView bottomNavigationMenu; @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupBottomMenu(); } private void setupBottomMenu() { if (bottomNavigationMenu != null) { BottomNavigationViewHelper.removeShiftMode(bottomNavigationMenu); bottomNavigationMenu.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { setupBottomMenuListener(item); return true; } }); } } private void setupBottomMenuListener(@NonNull MenuItem item) { switch (item.getItemId()) { //... } } } 

你为什么不简单地使用Kotlin Android绑定? Kotlin的扩展有助于绑定视图,而不用任何“bindView”或findViewById代码来干扰业务逻辑。

看一看。 https://kotlinlang.org/docs/tutorials/android-plugin.html

尝试添加一个Unbinder到你的基类

 protected Unbinder mUnbinder; 

然后在你的每个子类中设置mUnbinder

 mUnbinder = ButterKnife.bind(this); 

这个链接讨论这个问题。 完成后(在检查为空之后),将在基类中调用Unbinder

如果/当你去一个完整的Kotlin实施,你可以完全放弃黄油刀。

感谢@Les和@Daryl Sze! 加入扩展加Unbinder实现了与活动Java相同的行为!

 this.mUnbinder = ButterKnife.bind(this) apply plugin: 'kotlin-android' apply plugin: 'android-apt' apply plugin: 'kotlin-android-extensions'