Gabrielle
Gabrielle

Reputation: 4991

How to modify marginTop by code?

I'm trying to find a way to modify marginTop for an EditText by code...I read about setLayoutParams but I get ForceClose and this message :

08-05 14:53:59.715: ERROR/AndroidRuntime(913): java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
08-05 14:53:59.715: ERROR/AndroidRuntime(913):     at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1291)
08-05 14:53:59.715: ERROR/AndroidRuntime(913):     at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1238)
08-05 14:53:59.715: ERROR/AndroidRuntime(913):     at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:279)
08-05 14:53:59.715: ERROR/AndroidRuntime(913):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:299)
08-05 14:53:59.715: ERROR/AndroidRuntime(913):     at android.view.View.measure(View.java:7964)

Can anyone explain what should I do?

giveuser = (EditText) findViewById(R.id.txt_username);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(5,5,5,5);
        giveuser.setLayoutParams(lp);

and in xml :

<EditText android:id="@+id/txt_username"
        android:layout_height="wrap_content" android:layout_width="350px"
        android:layout_centerHorizontal="true" android:layout_below="@+id/loginsubtitle"
        android:layout_marginTop="180dip" android:singleLine="true"
        android:hint="Identifiant" />

Upvotes: 2

Views: 9546

Answers (3)

Vineet Shukla
Vineet Shukla

Reputation: 24031

try this:

LayoutParams params = EditTextName.getLayoutParams();
params.setMargins(left, top, right, bottom);
EditTextName.setLayoutParams(params);

Upvotes: 6

Cedekasme
Cedekasme

Reputation: 2037

Instead of create a new LayoutParams, you have to get the LayoutParams from your EditText. You can try this:

EditText giveuser = (EditText) findViewById(R.id.txt_username);
LayoutParams lp = giveuser.getLayoutParams();
lp.setMargins(left, top, right, bottom);
giveuser.setLayoutParams(lp);

Upvotes: 0

SnowyTracks
SnowyTracks

Reputation: 1985

Class cast exceptions I normally find by my R file being out of date, try cleaning your project and re-building

Upvotes: 0

Related Questions