Kotlin layout_gravity Programmatically (KLGP)


KLGP:   SOLD       




Hi dev, for normal cases of creating UI/UX for Android apps, we usually do it in the xml file, but on this occasion I want to share a different experience than usual, not normal.

Okay, this time we have to complete a case study on how to create an interactive and dynamic UI/UX, one of which is related to attributes  layout_gravity.

In principle, this kind of thing can also be done for other types of attributes in Android components.

Essentially, we will organize it  layout_gravity in a different way. Basically, this technique requires you to choose  LayoutParams depending on the parent. This can be  RelativeLayout,  LinearLayout etc...

Java

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

button.setLayoutParams(params);

Kotlin

val params = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
    weight = 1.0f
    gravity = Gravity.TOP
}

Example of Creating alignParentEnd Programmatically

Hi dev, still in order to continue the material above, so there are a few differences for other attributes, such as setting  layout_alignParentEnd. So to set the attribute into java code, you can use the method  addRule() from  RelativeLayout.LayoutParams, example;

// Create the LayoutParams
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

// Add all the rules you need
params.addRule(RelativeLayout.ALIGN_PARENT_END);

// Once you are done set the LayoutParams to the layout
relativeLayout.setLayoutParams(params);

Post a Comment

Previous Next

نموذج الاتصال