add view dynamically in a fragment

前端 未结 2 779
无人共我
无人共我 2021-01-28 15:20

I need to show some information in an agenda style, so i\'m using fragment to show the information in the different days. Every day have some column to showing the room.

2条回答
  •  不思量自难忘°
    2021-01-28 15:20

    I was facing similar problem and solved it the same way. My app has a main activity and two fragments. First fragment is a List Fragment which shows a list of formula. On clicking any formula a FormulaExpressionFragment, showing expressions for the formula, replaces the FormulaTitlesFragment. I wanted to dynamically add layout containing a calculator for the formula expression in the FormulaExpressionFragment. This is how I achieved it.

    public class FormulaExpressionsFragment extends Fragment {
    
    private TextView mTextView;
    private TextView mFormulaTitle;
    LinearLayout formulaExpressionsLayout;
    View rootView;
    View formulaCalculator;
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            }
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            rootView = inflater.inflate(R.layout.fragment_formula_expressions, container, false);
            return rootView;
        }
    void displayFormulaExpression(int position){
        mTextView = (TextView) getView().findViewById(R.id.formula_expression_view);
        mFormulaTitle = (TextView) getView().findViewById(R.id.formula_title_view);
        mTextView.setText(getResources().getTextArray(R.array.formula_expressions)[position]);
        mFormulaTitle.setText(getResources().getTextArray(R.array.formula_titles)[position]);
        mFormulaTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    }
    
    void displayFormulaCalculator(int position){
        formulaExpressionsLayout = (LinearLayout) rootView.findViewById(R.id.formula_expression_layout);
        LayoutInflater inflater = LayoutInflater.from(getActivity().getApplicationContext());
        formulaCalculator = inflater.inflate(R.layout.formula_1, formulaExpressionsLayout, false);
        formulaExpressionsLayout.addView(formulaCalculator);
    

    fragment_formula_expressions.xml

    
    
    
    

    formula_1.xml

    
    
    
    
    

    Pay special attention to

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    

    they should be set to "wrap_content" otherwise the view added below them will not show up in the layout as the top view will take all the display height.

提交回复
热议问题