自定义视图未显示在图形布局中

时间:2014-04-22 21:12:43

标签: android android-custom-view graphical-layout-editor

我创建了一个自定义Button,TextView和ImageView。这些都不能在任何XML的图形布局中正确显示。它不是显示带有自定义字体的按钮或文本,而是显示一个巨大的灰色框,其中包含我正在调用的自定义类的名称。如何在预览中显示这些内容?

public class FontTextView extends TextView {

public static Typeface FONT_NAME;

public FontTextView(Context context) {
    super(context);
    if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "font.ttf");
    this.setTypeface(FONT_NAME);
}
public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "font.ttf");
    this.setTypeface(FONT_NAME);
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "font.ttf");
    this.setTypeface(FONT_NAME);
}

<com.example.gesturetest.FontTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text placeholder" />

1 个答案:

答案 0 :(得分:2)

您可以在自定义视图中执行此操作:

if(!isInEditMode()){
   // Your custom code that is not letting the Visual Editor draw properly
   // i.e. thread spawning or other things in the constructor
}

Reference

在customView

的构造函数中执行此操作
public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    if (!isInEditMode()) {
        createTypeface(context, attrs); //whatever added functionality you are trying to add to Widget, call that inside this condition. 
    }

}