Adding extension to RelativeLayout


#1

In my android app, the below works fine to useRelativeLayout:

main_layout.addView(card1)
main_layout.addView(card2,
        RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT).apply {
            addRule(RelativeLayout.BELOW, card1.id)
        })

main_layout.addView(Settings(this),
        RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT).apply {
            addRule(RelativeLayout.BELOW, card2.id)
        }
)

As seen, I used the below code more than once, is there a way to simplify it, and avoid keeping rewriting it using Kotlin extensions?:

RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT).apply { .. }

#2

Yes, put the extension function on the (base) type of card2, Settings(this) and other views that you want to set the layout parameters of.


#3

sample code pls :slight_smile:


#4

Well, how would sample code help you become a better developer?

Let’s start with a question: How would you prevent the duplicate code with a normal function?


#5

By defining a variable, or another function


#6

Sorry, what I meant was: Can you post the code showing how you remove the code duplication using a normal function?