Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 2 Current »

You can choose to create a view inside the layout or create the view programmatically and add it to the layout later.

View in Layout File

This code goes inside the root of your layout file.

# activity_main.xml
...
<LinearLayout
    android:id="@+id/wrapper"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true">
</LinearLayout>
...

Get this view from an activity or fragment, a way to do it could be:

# MainActivity.kt

val wrapper = findViewById(R.id.wrapper)

View Programmatically

# MainActivity.kt
    // Get the root layout of the activity
    val parent = findViewById<ViewGroup>(R.id.main_layout) as RelativeLayout

    // Create your custom layout
    val wrapper = LinearLayout(this)
    wrapper.orientation = LinearLayout.HORIZONTAL

    // parameters for the wrapper inside a relative layout
    val params = RelativeLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT
    )
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
    params.addRule(RelativeLayout.CENTER_HORIZONTAL)
    
    wrapper.layoutParams = params
    
    // add the wrapper to the main layout
    parent.addView(wrapper)
  • No labels