【问题标题】:Custom Views not showing in Graphical Layout自定义视图未显示在图形布局中
【发布时间】:2014-04-22 21:12:43
【问题描述】:

我创建了一个自定义按钮、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" />

【问题讨论】:

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


【解决方案1】:

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

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

}

【讨论】:

  • 有帮助,但是,我需要将它放在我的 onLayout() 方法中,以便我获取 LayoutParams 并对其进行修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多