【问题标题】:setId() for programmatically generated FragmentsetId() 用于以编程方式生成的片段
【发布时间】:2021-05-28 14:54:31
【问题描述】:

我是安卓开发新手。

我正在尝试制作一个通知菜单,所以我制作了一个片段类:

class NotificationFragment {
    private String name;

    public NotificationFragment() {}

    public NotificationFragment(String name) {
        this.name = name;
    }

    public String getName() {return this.name;}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.notification_fragment, container, false);
    }
}

现在我想在我的屏幕上加载一个通知:

private List<int> notifications = new ArrayList<>();

private ConstraintLayer notification_layout = findViewById(R.id.aConstraintLayoutToHoldNotifications);

public load_notification(int i) {
    NotificationFragment cn = new NotificationFragment("TestName"+i);
    FragmentFrame ff = new FragmentFrame(this);
    int last_id = (notifications.size() >= 1 ? notifications.get(notifications.size() - 1) : ConstraintSet.PARENT_ID);
    int toObjectSide = (last_id == ConstraintSet.PARENT_ID? ConstraintSet.TOP : ConstraintSet.BOTTOM);

    int ff_id = View.generateViewId();
    ff.setId(ff_id);
    notification_layout.add(ff);

    ConstraintSet cs = new ConstraintSet();
    cs.clone(notification_layout);
    cs.connect(
        ff_id,
        ConstraintSet.TOP,
        last_id,
        toObjectSide
    );
    cs.applyTo(notification_layout);

    getSupportFragmentManager()
        .beginTransaction()
        .add(notificationLayerID, cn, "UIFragment")
        .commit();

    notifications.add(ff_id);
}

现在可以正常工作了。

但是,如果我再次调用它,它会引发错误java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet,所以我尝试进行一些调试,我认为片段是需要 id 的,但片段类没有 setId()。

问题:

1) is there a way to set the id of a programmatically generated Fragment?
2) if not, is there a "hack" around this?
3) is there something that i am missing and i don't need an id on the Fragment?

注意

我尽量删减代码,帖子应该是最小可执行示例

【问题讨论】:

    标签: java android android-fragments mobile-development


    【解决方案1】:

    这应该回答问题 1,但它可能无法解决您的问题。

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view =  inflater.inflate(R.layout.notification_fragment, container, false);
            view.setId(View.generateViewId());
            return view;
        }
    

    或者在你的 notification_fragment.xml 中添加一个 Id 到根元素,但是如果你同时有两个通知,你很可能会遇到重复的 ids 问题。

    【讨论】:

    • 是的,行得通。如果我尝试使用fragVariable.getView() 会起作用吗,如果视图已经存在,getView() 的结果会没有 id 吗?
    • 我怀疑getView() 依赖于视图ID,只是它的视图。但是像findViewById(int) 这样的东西肯定行不通,因为没有 id 代表视图。
    猜你喜欢
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2012-04-24
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多