how to use custom views in layout xml

落爺英雄遲暮 提交于 2019-12-06 05:00:31

You have a NullPointerException in one of your constructors. I can not exactly tell which one, as the StackTrace says line 27, which is an empty line in the code you posted.

You should re-run your code, check the first line of the stack trace in your code. I would guess it's this line:

duration = movie.duration();

and the movie object is null.

Damian Petla

The problem is not with your code but displaying custom view in Graphical Layout. Drawing views rely on device features. To see your custom view properly you have to use the isInEditMode() method in your custom view implementation. Based on that method, you have to implement alternative initialization and drawing.

I think you want your xml file object to be like this:

<com.spazio.digitale.GIFView android:id="@+id/gIFView1"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_gravity="center" />

assuming that your package is com.spazio.digitale which I'm not totally sure of from what you've posted.

Try this it work for me

public class MyOwnTextView extends TextView {

    public MyOwnTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub

    }

    public MyOwnTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

    }
    public MyOwnTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

    }

    public void setTypeface(Typeface tf, int style) {
        if(!this.isInEditMode()){
        Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");
        Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Roboto-Light.ttf");

        if (style == Typeface.BOLD) {
            super.setTypeface(boldTypeface/*, -1*/);
        } else {
            super.setTypeface(normalTypeface/*, -1*/);
        }
        }

    }   

}

then at the xml

<com.xxxxx.appname.MyOwnTextView

          android:layout_width="fill_parent"
          android:layout_height="fill_parent"

        />

My problem was that a ttf font was placed in custom "fonts" folder under assets folder. Error when displayed xml layout:

The following classes could not be instantiated:
----
Tip: Use View.isInEditMode() in your custom views to skip code when shown...

Then, I placed the font under root assets folder, rebuilt project and, magically, all works and the xml layout was showed ok.

Then, I dragged the font to the "fonts" folder again trough ide, rebuilt project and the xml layout remains showed ok.

I don´t have any idea why this operation worked but if it can help anyone, ok.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!