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

Zee*_*ran 2 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);
}
Run Code Online (Sandbox Code Playgroud)

<com.example.gesturetest.FontTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text placeholder" />
Run Code Online (Sandbox Code Playgroud)

Xar*_*mer 5

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

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

参考

在 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. 
    }

}
Run Code Online (Sandbox Code Playgroud)