Hello I have bellow Button : ```<Button a...
# android
n
Hello I have bellow Button :
Copy code
<Button
    android:id="@+id/profileButton"
    android:layout_width="28dp"
    android:layout_height="28dp"
    android:layout_marginStart="200dp"
    android:layout_marginTop="7dp"
    android:background="@drawable/round_corners_avatar"
    android:text="AL"
    android:textColor="#FFFFFF"
    android:onClick="profileBtnClicked"
    android:textSize="16sp" />
I would like to change the
android:layout_marginStart
parameter based on the information i receive from
resources.displayMetrics.density
However I do not know how to access marginStart parameter programatically. Any clues would be much appreciated.
😶 1
a
you can’t do that in xml .. you can do in the java/kotlin file
n
Thank you for replying. Do you know the exact method that allows doing this? Example :
val btn = FindViewById(R.id.profilebtn)
btn.setMarginStart() ???
a
Copy code
LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
params.setMargins(left, top, right, bottom);
Copy code
button.setLayoutParams(params);
n
Thank you. Did you ever come across the top and bottom parameter being unresolved error?
a
what was that error ?
check the type for top & bottom
n
It is
Unresolved reference : top
error
a
variables are unresolved check the scope or send the whole file
n
Which is weird because the variables are defined inside the file.
Maybe i made the wrong imports. I'll check.
Solved it by adding imports
Copy code
import android.R.attr.left
import android.R.attr.right
import <http://android.R.attr.top|android.R.attr.top>
import android.R.attr.bottom
✅ 1
a
Great
n
I am guessing the marginStart property is equal to the left parameter here?
a
you’re right
n
So if i want to change
marginStart = 358dp
to
marginStart = 340dp
i change
left = 340
✅ 1
Alright thanks. I'll give it a shot.
🤛 1
After running I am getting a casting error for ConstraintLayout
java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
I wonder if
FrameLayout.LayoutParams
would make it work?
a
importing based on the parent layout type would be better choice
n
Yes changing it to
FrameLayout.LayoutParams
fixed it. Thank you.
✅ 1
@Android Mahi Just one more question. If i only change the
left
parameter and keep the rest of it the same then those would default to whatever the initial XML file defined them as right? So for example
android:layout_marginTop="7dp"
means that top ill default to
7dp
?