有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java“commitNow()”和“postDelayed”是如何让这段代码工作的?

我试着做一些零碎的工作。我在布局中放入了一个recyclerview布局,并在片段的onCreateView中初始化了recyclerview。 最后,我将recyclerview的pos动态设置为其项目

我有这样的代码,使它能够正确地与commitNowpostDelayed一起工作,即使延迟为0毫秒,但我不知道为什么:

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.parentLayout, popupFragment)
                .commitNow();
        new Handler().postDelayed(()->popupFragment.show(), 0);

但我试过:

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.parentLayout, popupFragment)
                .commitNow();
        popupFragment.show();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.parentLayout, popupFragment)
                .commitNowAllowingStateLoss();
        popupFragment.show();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.parentLayout, popupFragment)
                .runOnCommit(()->popupFragment.show())
                .commitNowAllowingStateLoss();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.parentLayout, popupFragment)
                .runOnCommit(()->popupFragment.show())
                .commitNow();

它们都有一个未初始化的高度

根据我的猜测,这是关于postDelayed使代码在下一个循环中运行,然而,runOnCommit似乎也会先进行提交,然后再运行可运行的,为什么这不起作用


共 (1) 个答案

  1. # 1 楼答案

    如果您想要一个“弹出”片段,建议您像这样利用AlertDialog类(并从onCreateView中重构代码,因为您不能保证从onCreateView中引用活动):

    @Override
    public void onViewCreated(View view, Bundle onSaveInstanceState) {
        super.onViewCreated(view, onSaveInstanceState);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View popupFragmentsResourceView = inflater.inflate(R.layout.fragment_popup_view, null);
        builder.setView(popupFragmentsResourceView);
        //grab controls here
        //RecyclerView rv = popupFragmentsResourceView.findViewById(R.id.some_id);
        //rv.setAdapter(new CustomAdapter(getActivity));
        //set a click button for your dialog builder
        builder.show();
    }