【发布时间】:2014-08-29 09:58:45
【问题描述】:
我的 CustomTextView 有问题。我试图从我的layout-xml 文件中获取一个自定义值,并在我的setText() 方法中使用它。不幸的是,setText() 方法在 constructor 之前被调用,因此我不能在此方法中使用自定义值。 p>
这是我的代码(分解为相关部分):
CustomTextView.class
public class CustomTextView extends TextView {
private float mHeight;
private final String TAG = "CustomTextView";
private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "in CustomTextView constructor");
TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
this.mHeight = values.getDimension(R.styleable.CustomTextView_cHeight, 20);
}
@Override
public void setText(CharSequence text, BufferType type) {
Log.d(TAG, "in setText function");
Spannable s = getCustomSpannableString(getContext(), text);
super.setText(s, BufferType.SPANNABLE);
}
private static Spannable getCustomSpannableString(Context context, CharSequence text) {
Spannable spannable = spannableFactory.newSpannable(text);
doSomeFancyStuff(context, spannable);
return spannable;
}
private static void doSomeFancyStuff(Context context, Spannable spannable) {
/*Here I'm trying to access the mHeight attribute.
Unfortunately it's 0 though I set it to 24 in my layout
and it's correctly set in the constructor*/
}
}
styles.xml
<declare-styleable name="CustomTextView">
<attr name="cHeight" format="dimension"/>
</declare-styleable>
layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ctvi="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.mypackage.views.CustomTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/my_fancy_string"
android:textSize="16sp"
ctvi:cHeight="24dp" />
</LinearLayout>
作为证明 - 这是 LogCat 输出:
30912-30912/com.mypackage.views D/CustomTextView﹕ in setText function
30912-30912/com.mypackage.views D/CustomTextView﹕ in CustomTextView constructor
如您所见,setText() 方法在构造函数之前被调用。这有点奇怪,我不知道我需要更改什么才能在 setText 方法中使用我的自定义属性 (cHeight)。
提前感谢您的帮助!
【问题讨论】:
-
感谢您提出这个问题,我只花了一个小时才弄清楚为什么我在构造函数中初始化的自定义属性在 setText 中为空。在第一行的构造函数中调用 super(..) 是愚蠢的 Java 限制,否则您将能够在实际调用 setText 之前初始化自定义属性
标签: android textview android-custom-view