base活动扩展活动viewbinding崩溃

2fjabf4q  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(701)

我的基本活动扩展了我的所有其他活动。基本活动具有工具栏、进度条和其他在整个活动中类似的逻辑方法等功能
从butterknife迁移到viewbinding后,从父基扩展的子活动无法访问其中的方法,应用程序将崩溃。
下面是基本活动代码

pubic class BaseActivity extends AppCompatActivity {

    private ActivityBaseBinding activityBaseBinding;

    @Override
    public void setContentView(int layoutResID) {
        activityBaseBinding = ActivityBaseBinding.inflate(getLayoutInflater());

        View  view = getLayoutInflater().inflate(layoutResID, activityBaseBinding.container, false);

        if (layoutResID == R.layout.activity_home) {
            activityBaseBinding.toolbarTitle.setVisibility(View.GONE);
        } else if (layoutResID == R.layout.activity_my_account) {
            activityBaseBinding.toolbarTitle.setVisibility(View.VISIBLE);
        } else {
            activityBaseBinding.toolbarTitle.setVisibility(View.GONE);
        }

        activityBaseBinding.container.addView(view);
        setContentView(activityBaseBinding.getRoot());
        activityBaseBinding.imgBackArrow.setOnClickListener(v -> onBackPressed());

    }

如果我试图从子活动访问基中的工具栏,这就是我得到的错误
java.lang.runtimeexception:无法启动活动组件信息{com.iowave.scheduler/com.example.myaccount.views.myaccount}:java.lang.nullpointerexception:尝试读取空对象引用上的字段“com.google.android.material.appbar.materialtoolbar com.example.databinding.activitybasebinding.toolbarttitle”
这是我孩子活动的代码

public class MyAccount extends BaseActivity implements MyAccountImpl {

    private NavController navController;

    private ActivityMyAccountBinding activityMyAccountBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMyAccountBinding = ActivityMyAccountBinding.inflate(getLayoutInflater());
        View view = activityMyAccountBinding.getRoot();
        setContentView(view);
             }
}

据我所知,视图绑定只是绑定子视图,并从后台删除所有其他绑定。

oyxsuwqo

oyxsuwqo1#

将此方法用于基本活动模式。

abstract class  BaseActivity1<Binding extends ViewBinding> extends AppCompatActivity {

    Binding binding;

    abstract  Binding getBinding();

    void  initBinding(){
        binding=getBinding();
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.initBinding();
        setContentView(binding.getRoot());
    }  
}

然后

class MainActivity extends BaseActivity1<ActivityMainBinding>{
    @Override
    ActivityMainBinding getBinding(){
        return ActivityMainBinding.inflate(getLayoutInflater());
    }
}

相关问题