How to Programmatically Add Views to Views

后端 未结 7 648
春和景丽
春和景丽 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:55

    The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.

    All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild() method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].

    Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:

    Step 1:

    In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".

    Step 2 Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent">
    
    </TextView>
    

    BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.

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

    If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.

    Step 3

    In your onCreate method, do this :

    FrameLayout frameLayout = findViewById(R.id.container);
                    TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
                    frameLayout.addView(textView);
    

    (Note that setting last parameter of findViewById to null and adding view by calling addView() on container view (frameLayout) is same as simply attaching the inflated view by passing true in 3rd parameter of findViewById(). For more, see this.)

    0 讨论(0)
提交回复
热议问题