我的最终目标是让用户能够在活动中使用动态生成的内容(基于用户输入)在标签之间切换。我正在尝试创建一个动态布局,并将其作为片段内的布局加载。我的代码抛出错误,因为我试图提供的布局不是xml资源。我正在尝试做什么呢?
public static class JobsFragment extends Fragment{
LinearLayout l;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//set button vars here
Log.i("aaa","called frag onCreate");
l=new LinearLayout(getActivity());
Button b=new Button(getActivity());
b.setText("HI");
l.addView(b);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Log.i("aaa","called frag onCreateView()");
//View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
View rootView = inflater.inflate(l, container, false);
return rootView;
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter{
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new JobsFragment();
return fragment;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
}
答案 0 :(得分:0)
您需要以编程方式添加布局宽度和高度。 没有它,它将抛出未提供的强制布局参数的错误。 添加LayoutParams是方法名称
答案 1 :(得分:0)
使片段构造函数接受linearlayout作为参数,并使用此字段从onCreateView返回
类似于伪造的代码
CustomFragment{
private LinearLayout mLayout;
CustomFragment(LinearLayout layout){
mLayout=layout;
| }
onCreatView(....)
{
return mLayout;
}
}