How to Programmatically Add Views to Views

后端 未结 7 667
春和景丽
春和景丽 2020-11-22 12:55

Let\'s say I have a LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I\'m not asking how it\'s done

7条回答
  •  醉酒成梦
    2020-11-22 13:33

    for anyone yet interested:

    the best way I found is to use the inflate static method of View.

    View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);
    

    where yourViewXML is something like R.layout.myView

    please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

    so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

        View view = getView(); // returns base view of the fragment
        if (view == null)
            return;
        if (!(view instanceof ViewGroup))
            return;
    
        ViewGroup viewGroup = (ViewGroup) view;
        View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);
    

提交回复
热议问题