简体   繁体   English

将以编程方式创建的LinearLayout作为资源添加到Fragment中的View

[英]Add Programatically created LinearLayout as resource to View in Fragment

My eventual goal is to have users be able to switch between tabs with dynamically generated content (based on user input) in an activity. 我最终的目标是使用户能够在活动中具有动态生成的内容(基于用户输入)的选项卡之间切换。 I am trying to create a dynamic layout and have it load as the layout within a fragment. 我正在尝试创建动态布局,并将其作为片段中的布局加载。 My code is throwing an error because the layout I am trying to provide is not an xml resource. 我的代码抛出错误,因为我要提供的布局不是xml资源。 Is what I'm trying even possible to do? 我正在尝试做的可能吗?

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);
        }   
    }

} }

You need to add layout width and height programatically. 您需要以编程方式添加布局的宽度和高度。 Without which it will throw error about mandatory layout parameters not provided. 没有它,它将抛出有关未提供强制布局参数的错误。 addLayoutParams is the method name addLayoutParams是方法名称

Make the fragment constructor accept linearlayout as parameter and use this field to be return from onCreateView 使片段构造函数接受linearlayout作为参数,并使用此字段从onCreateView返回

Something like following psuedo code 像下面的伪代码一样

  CustomFragment{
   private LinearLayout mLayout;

    CustomFragment(LinearLayout layout){
     mLayout=layout;
|   }

    onCreatView(....)
    {
     return mLayout;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM