Android - Dynamically Add Views into View

后端 未结 5 2001
情书的邮戳
情书的邮戳 2020-11-22 03:58

I have a layout for a view -



        
5条回答
  •  伪装坚强ぢ
    2020-11-22 04:17

    Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

    LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.your_layout, null);
    
    // fill in any details dynamically here
    TextView textView = (TextView) v.findViewById(R.id.a_text_view);
    textView.setText("your text");
    
    // insert into main view
    ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
    insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    

    You may have to adjust the index where you want to insert the view.

    Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

提交回复
热议问题