How to use addView to add view to layout?

后端 未结 4 2215
南笙
南笙 2021-02-18 16:36

I have read probably all posts and documentation but I still can\'t solve this issue.

I want to use addView() method to add view to the existing (running) l

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-18 17:09

    You forgot to specify the LayoutParameters for the newly added view.

    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
        TextView text=new TextView(this);
        text.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        text.setText("test");
        layout.addView(text);
    

    EDIT

    The GridView with an id of @+id/gridview is defined with a layout height of fill_parent, leaving you with no space to add a new view. Changing its height to wrap_content may solve your problem.

    Adding my comment to this post to help others easily verify the solution.

提交回复
热议问题