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.
TextView tv1 = new TextView(this); tv1. setPadding(5, 0, 5, 0); tv1. setLayoutParams(new LayoutParams(LayoutParams.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With