Android - Dynamically Add Views into View

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

I have a layout for a view -



        
5条回答
  •  失恋的感觉
    2020-11-22 04:37

    To make @Mark Fisher's answer more clear, the inserted view being inflated should be a xml file under layout folder but without a layout (ViewGroup) like LinearLayout etc. inside. My example:

    res/layout/my_view.xml

    
    
    

    Then, the insertion point should be a layout like LinearLayout:

    res/layout/activity_main.xml

    
    
    
        
    
        
    
    
    

    Then the code should be

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
    
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.my_view, null);
        ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
        main.addView(view, 0);
    }
    

    The reason I post this very similar answer is that when I tried to implement Mark's solution, I got stuck on what xml file should I use for insert_point and the child view. I used layout in the child view firstly and it was totally not working, which took me several hours to figure out. So hope my exploration can save others' time.

提交回复
热议问题