通过文档,查到TextView下有这么个方法setLayoutParams(ViewGroup.LayoutParams params),但是ViewGroup.LayoutParams这个东西,并没有setMargins方法,LinearLayout.LayoutParams才有,这可咋办?
手册上这样讲public void setLayoutParams (ViewGroup.LayoutParams params), 『该方法提供一些参数给父视图,指定了该view在父视图中的位置。
如果需要动态改变TextView(或者其它View)的margin属性(android:layout_marginTop, android:layout_marginBottom, android:layout_marginLeft, android:layout_marginRight),最好是通过代码动态添加这个View,而不是在layout中定义该View。
如果父视图是LinearLayout,那么就可以直接调用textView.setLayoutParams(params),然后在添加textView到LinearLayout:
方案1、如果这个控件实在XML中定义的 比如Textview
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) textview.getLayoutParams(); lp.leftMargin = 0; textview.setLayoutParams(lp);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(10,10,10,10);//4个参数按顺序分别是左上右下 textview.setLayoutParams(layoutParams);
第一种方法必须在控件已经存在的情况下才可以用。
通过以上内容的阐述,相信大家对如何通过代码设置Android动态设置的margin参数的方法已经有了进一步的了解,更多动态设置margin的问题,欢迎关注群英网络或到群英官网咨询客服。免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。