gpt4 book ai didi

android - 在 onCreateView() fragment 中设置动态布局

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:19 26 4
gpt4 key购买 nike

我用,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

MyView myView = new MyView(getActivity());
myView.addViews(getViews());
return myView;
}

我知道 public void onActivityCreated (Bundle savedInstanceState){}onCreateView(); 之后调用

我将需要 onCreateView() 中的上下文来扩充自定义布局。如何在 onActivityCreated() 之前一直获取有效上下文(使用 getActivity())?

可能的解决方案:

View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment, container, false); //Contains empty RelativeLayout
return view;
}


//Now that we have activity, create custom views and add it to the empty container
public void onActivityCreated (Bundle savedInstanceState){
RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.layout);
MyView myView = new MyView(getActivity());
layout.add(myView);
}

但是这个方法增加了一个额外的 View 层次结构。

最佳答案

您可以使用与 LayoutInflater 关联的 Context 对象:

MyView myView = new MyView( inflater.getContext() );

关于android - 在 onCreateView() fragment 中设置动态布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com