我以编程的方式创建了一个textView。现在我需要以编程的方式给这个文本视图分配一个样式。(不仅是TextAppearance,还有左边距、填充等)。所有这些样式属性都是在xml文件中定义的。
TextView tv = new TextView(this);
发布于 2013-04-01 08:56:29
设置填充非常简单。但利润率有点微不足道。请看下面的内容。
TextView tv = new TextView(this);
//setting padding left top right bottom
tv.setPadding(10, 10, 10, 10);
//setting left margin
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
tv.setLayoutParams(llp);
发布于 2013-04-01 08:56:59
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setPadding(left, top, right, bottom);
left- padding to left
top - padding to right
right -padding to right
bottom -padding to bottom
有关更多样式,请查看下面的链接。请参阅setter方法。您可以设置文本大小、背景颜色等。
http://developer.android.com/reference/android/widget/TextView.html。
发布于 2013-04-01 08:57:36
使用布局参数设置此属性。
TextView t = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(heightInPixels, widthInPixel);
params.setMargins(left, top, right, bot);
t.setLayoutParams(params);
mLinearLayout.addView(t);
编辑:
如果在attrs.xml文件中定义了自己样式表,则必须在构造函数中创建自己的Textview和处理所需的属性。它用于处理来自XML的属性。对于java的定义,你必须创建"set method“。
public class MyTextView extends TextView
{
String _stringValue;
public MyTextView(Context c)
{
this(c, null);
}
public MyTextView(Context c, AttributeSet attrs)
{
this(c, attrs, 0);
}
public MyTextView(Context c, AttributeSet attrs, int defStyle)
{
super(c, attrs, defStyle);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.MyStyleAble);
_stringValue = a.getString(R.styleable.MyStyleAble_stringValue);
a.recycle(); //don't forget this line!
}
public void setStringValue(String s)
{
_stringValue = s;
}
}
编辑
这里在代码中使用了MyTextView。只需使用标准构造函数创建它。
MyTextView t = new MyTextView(context);
然后设置可设置样式的值。在我的示例中,它是字符串值。
t.setStringValue("My string text");
然后使用layoutParams。
t.setLayoutParams(params);
并将新创建的TextView添加到某个布局中。例如LinearLayout。
mLinearLayout.addView(t);
我忘了说,只有当您需要在attrs.xml文件中设置属性时,才必须定义可设置样式的int。然后像这样使用它。
<my.package.name.MyTextView
xmlns:custom="http://schemas.android.com/apk/res/my.package.name"
custom:stringValue="some string text"
//and also you can use standart android:... attributes
/>
https://stackoverflow.com/questions/15740375
复制相似问题