前言
代码生成控件时,有时候view的padding和margin,drawablRight,字体颜色的背景选择器,背景颜色的选择器和一些属性可能会和布局文件xml中的设置不一样,注意到这些细节后,我就整理了一些,网友们经常出现的设置问题。
1、代码生成TextView
TextView textView = new TextView(this);
textView.setText(mStrs[i]);
textView.setPadding(15, 5, 15, 5);
textView.setTextColor(color);
textView.setTextColor(getResources().getColor(R.color.text_black2white_cb));
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(15, 15, 15, 15);
textView.setLayoutParams(params);
textView.setBackgroundResource(R.color.black);
padding需要textview去设置,而与其他textview之间的上下左右的距离,应该使用LayoutParams 去设置才起作用。
2、CheckBox的android:button=”@null”属性代码设置如下:
checkBox.setButtonDrawable(new ColorDrawable());
3、设置XML中控件的drawableRight等
android:drawablePadding="10dp"
android:drawableRight="@drawable/cb_drawable_right"
代码设置为:
//四个参数分别为,左,上,右,下的图片,不需要设置就传0
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0, 0, R.drawable.xuanzhongxian);
TextView.setCompoundDrawablePadding(10);//设置图片和text之间的间距
PS:设置背景选择器时,失败的话可以看我前一篇文章。
Android,setTextColor等背景选择器设置失败问题,及多种设置方法