简体   繁体   中英

Button at bottom of programmatically created layout

I made a linear layout where I have a view and a button. And inside that linear layout I am also adding some more elements but programmatically. Here is the code:

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <View android:layout_width="match_parent"
            android:layout_height="20dp"
            android:background="@color/transparentBlack1"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="40dp"
            android:shadowColor="@color/noColor"
            android:background="@color/transparentBlack1"
            android:text="@string/NewButton"
            android:textSize="30sp"
            android:gravity="center"
            android:textColor="@color/background2"
            android:onClick="addLine"/>
    </LinearLayout>

With the addLine function I just add another element in the layout. Is there any way to keep the button at the bottom of every element inside the layout, so other elements that I create with code will be above the button?

I guess you use linearLayout.addView(view); to add your views, correct? You can specify where the view should be added like the following:

linearLayout.addView(view, linearLayout.getChildCount() - 1);

This should add it between the view and the button.

See documentation for method explanations:

Try make that button outside that layout, something like this:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:id="@+id/container"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <View android:layout_width="match_parent"
                  android:layout_height="20dp"
                  android:background="@color/transparentBlack1"/>

         </LinearLayout>

        <Button
            android:layout_width="70dp"
            android:layout_height="40dp"
            android:shadowColor="@color/noColor"
            android:background="@color/transparentBlack1"
            android:text="@string/NewButton"
            android:textSize="30sp"
            android:gravity="center"
            android:textColor="@color/background2"
            android:onClick="addLine"/>
    </LinearLayout>

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM