Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change Margin of TextView

Tags:

android

I have TextView added Programmatically in to LinearLayout and on some external events I want to decrease bottom margin of that TextView to -10, for that I tried following.

LinearLayout.LayoutParams lastTxtParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lastTxtParams.setMargins(0, 0, 0, -10); mOldTextView.setLayoutParams(lastTxtParams); mOldTextView.invalidate(); 

Is the right way of modifying Margin of widget that has been added to View?
Some how it is not working.

like image 301
User7723337 Avatar asked Jan 27 '11 08:01

User7723337


People also ask

How do I set margin of TextView in android programmatically in Kotlin?

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


2 Answers

TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText); forgot_pswrd.setOnTouchListener(this);      LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom); forgot_pswrd.setLayoutParams(llp); 

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

like image 166
Debarati Avatar answered Nov 17 '22 07:11

Debarati


Your layout in xml probably already has a layout_margin(Left|Right|etc) attribute in it, which means you need to access the object generated by that xml and modify it.

I found this solution to be very simple:

ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mTextView         .getLayoutParams();  mlp.setMargins(adjustmentPxs, 0, 0, 0);  break; 

Get the LayoutParams instance of your textview, downcast it to MarginLayoutParams, and use the setMargins method to set the margins.

like image 34
Danny Armstrong Avatar answered Nov 17 '22 06:11

Danny Armstrong