【发布时间】: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