Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android set margin programmatically

Tags:

after i press a button, i would like to move a textfield programmatically from the actual position + 20 margin left.

this is my xml file:

<RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:paddingTop="5dp"     android:paddingBottom="5dp">       <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/txtField"         android:layout_below="@+id/txtField2"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true"         android:layout_marginLeft="20dp"         android:layout_toLeftOf="@+id/Seperator"         android:layout_toStartOf="@+id/Seperator"         android:layout_marginRight="10p" />      ....   </RelativeLayout> 

i tried this code:

parameter = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); parameter.setMargins(30, 32, 10, 0); // left, top, right, bottom txtField.setLayoutParams(parameter); 

this works semi optimal. is there an way to use all the values of an xml file and only change the margin left value programmatically?

like image 857
Stack108 Avatar asked Mar 20 '16 14:03

Stack108


People also ask

How do I set margins to recyclerView programmatically?

margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.

How do I set margins in TextView?

TextView tv1 = new TextView(this); tv1. setPadding(5, 0, 5, 0); tv1. setLayoutParams(new LayoutParams(LayoutParams.


1 Answers

Try this code:

parameter =  (RelativeLayout.LayoutParams) txtField.getLayoutParams(); parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom txtField.setLayoutParams(parameter); 
like image 150
dieter_h Avatar answered Oct 11 '22 01:10

dieter_h