在xml中我们可以这样设置
<TextView
...
android:layout_centerHorizontal="true"
...
/>
现在需要用程序的方式实现。我有TextView实例,如何用程序的方式实现与xml中设置的相同的功能?
你应该在RelativeLayout.LayoutParams
中的addRule
方法
layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mTextView.setLayoutParams(layoutParams);
假设有一个调用的TextView存储在一个变量tv中:
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
tv.setLayoutParams(lp);