sonichy
sonichy

Reputation: 1478

Android: how to use code to change layout_marginTop of textview?

After setContentView(R.layout.activity_main), I want to use code to change only layout_marginTop of textview(android:layout_centerHorizontal="true").

tvcity = (TextView) findViewById(R.id.city);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 20, 0, 0);
tvcity.setLayoutParams(lp);

Centered changed to left-aligned.
setMargins(int left, int top, int right, int bottom) contains 4 parameters, but I only want to change the second parameter!

Upvotes: 1

Views: 390

Answers (2)

ranchuk
ranchuk

Reputation: 83

Try using the existing margins:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(lp.leftMargin, 20, lp.rightMargin, lp.bottomMargin);
tvcity.setLayoutParams(lp);

Upvotes: 0

Xiaoyu Yu
Xiaoyu Yu

Reputation: 725

Try replacing

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);

with this:

RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)tvcity.getLayoutParams();

Upvotes: 1

Related Questions