Add view to the top of FrameLayout

4.3k views Asked by At

main.xml:

<FrameLayout id="parent">
     <ImageView layout_width="match_parent" layout_height="match_parent"/>
</FrameLayout>

ActivityMain.java

onCreate() {
    super.onCreate();
    setContentView(R.layout.nain);

    ViewGroup parent = (ViewGroup) findViewById(R.id.parent);

    TextView textView = new TextView(this);
    textView.setText("Hello, world");

    parent.addView(textView);
    // parent.addView(textView, 0);
    // parent.addView(textView, 1);
    // parent.bringChildToFont(textView);
}

I inflated the code above as the content, and then, how can I add another view to the FrameLayout and it's on the top of the ImageView?

I had tried some several hours, but still don't know how to programmatically add another view to the top of the FrameLayout.

I found that it's easy to achieve the goal by add two children to the XML file. And at the end, I use a ViewStub and complete my work.

But I'm so curious about how to do this without a ViewStub.

my solution:

main.xml:

<FrameLayout id="parent">
     <ImageView layout_width="match_parent" layout_height="match_parent"/>

     <ViewStub id="stub">
</FrameLayout>

widget_text_view.xml:

<TextView />

ActivityMain.java

onCreate() {
    super.onCreate();
    setContentView(R.layout.nain);

    ViewStub stub = (ViewStub) findViewById(R.id.stub);
    stub.setLayoutResource(R.layout.widget_text_view);
    TextView textView = (TextView) stub.inflate();
}
1

There are 1 answers

1
Sajidkhan On

yes you can add item to the top of another view. android:layout_gravity attribute. visite This. Or This