封装dialog时一些不解的地方

一个点击事件失效的记录

下面是一个作为父类的dialog

js 复制代码
public abstract class BaseDialog <VDB extends ViewDataBinding> extends AppCompatDialog {

    protected VDB binding;

    public BaseDialog(@NonNull Context context) {
        super(context);
        binding = DataBindingUtil.inflate(
                getLayoutInflater(),
                getContentViewId(),
                null,
                false
        );
        setContentView(getContentViewId());
        processLogic();
    }


    protected abstract int getContentViewId();

    /**
    *处理业务逻辑
     * */
    protected abstract void processLogic();


}

这是他的一个子类

js 复制代码
public class GainDialog extends BaseDialog<DialogGainBinding> {
    public GainDialog(@NonNull Context context) {
        super(context);
        Log.d("dialog","22222");
       
    }
    
    @Override
    protected int getContentViewId() {
        return R.layout.dialog_gain;
    }

    @Override
    protected void processLogic() {
        binding.closeButton.setOnClickListener(v -> {
            dismiss();
        });
    }
    
}

可以看到在这个子类中,我们已经对closeButton设置了点击事件让其关闭,但是当我们运行之后,点击这个按钮发现并没有像我们预期之中一样关闭弹窗。 经过排查发现问题出现在父类的这一行代码

setContentView(getContentViewId());

如果把这行代码换成

setContentView(binding.getRoot());

点击事件就能成功响应了。

为什么会这样还没有仔细分析。除此之外,还有一个疑惑的的地方:就是当我们实例化GainDialog时用的是

GainDialog dialog = new GainDialog(MainActivity.this);

为什么还调用了父类里的构造方法

js 复制代码
public BaseDialog(@NonNull Context context) {
        super(context);
        binding = DataBindingUtil.inflate(
                getLayoutInflater(),
                getContentViewId(),
                null,
                false
        );
        setContentView(getContentViewId());
        processLogic();
    }
相关推荐
一条上岸小咸鱼7 分钟前
Kotlin 基本数据类型(五):Array
android·前端·kotlin
whysqwhw24 分钟前
Room&Paging
android
whysqwhw30 分钟前
RecyclerView超长列表优化
android
Tiger_Hu40 分钟前
Android系统日历探索
android
whysqwhw41 分钟前
RecyclerView卡顿
android
whysqwhw1 小时前
RecyclerView 与 ListView 在性能优化方面
android
檀越剑指大厂4 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android
MiyamuraMiyako5 小时前
从 0 到发布:Gradle 插件双平台(MavenCentral + Plugin Portal)发布记录与避坑
android
NRatel5 小时前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本
叽哥8 小时前
Kotlin学习第 1 课:Kotlin 入门准备:搭建学习环境与认知基础
android·java·kotlin