use*_*678 11 android textview android-custom-view
我的CustomTextView有问题.我正在尝试从我的layout-xml文件中获取自定义值并在我的setText()方法中使用它.不幸的是,在构造函数之前调用了setText()方法,因此我无法在此方法中使用自定义值.
这是我的代码(细分到相关部分):
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*/
}
}
Run Code Online (Sandbox Code Playgroud)
<declare-styleable name="CustomTextView">
<attr name="cHeight" format="dimension"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
就像一个证据 - 这里是LogCat输出:
30912-30912/com.mypackage.views D/CustomTextView? in setText function
30912-30912/com.mypackage.views D/CustomTextView? in CustomTextView constructor
Run Code Online (Sandbox Code Playgroud)
因此,您可以看到setText()在构造函数之前调用该方法.这有点奇怪,我不知道我需要改变什么才能cHeight在setText-method中使用我的自定义属性().
在此先感谢您的帮助!
| 归档时间: |
|
| 查看次数: |
4006 次 |
| 最近记录: |