繁体   English   中英

在XML布局中使用自定义视图

[英]Use Custom View In XML Layout

我有一个自定义视图:

public class Loading extends View {

    private long movieStart;
    private Movie movie;

    public Loading(Context context, InputStream inputStream) {
        super(context);
        movie = Movie.decodeStream(inputStream);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        super.onDraw(canvas);
        final long now = SystemClock.uptimeMillis();
        if(movieStart == 0)
            movieStart = now;
        final int relTime = (int)((now - movieStart) % movie.duration());
        movie.setTime(relTime);
        movie.draw(canvas, 0, 0);
        this.invalidate();
    }

}

如何在XML布局中使用此视图? 如何在XML布局中传递参数(Context,InputStream)?

How can I use this view in XML layout?

..

 <pacakge_of_class.Loading 
            android:id="@+id/y_view1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

http://developer.android.com/guide/topics/ui/custom-components.html

当从代码创建视图时会调用构造函数的一种form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file会调用一种形式的构造函数form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file

How can I pass the parameters 

https://stackoverflow.com/a/4495745/804447

在layout / main.xml中引用内部类View时出错

<view class="Your_package.MainClass$Loading" />

简短的答案是您不能直接这样做。

长答案是您可以间接地做到这一点。

通过全限定名(如其他人提到的)将视图添加到XML,然后:

您需要做的是从View实现普通的构造函数。 定义一个自定义属性,该属性声明用于在构造函数中创建InputStream的资源。 视图系统将自动为您提供上下文,然后您需要根据提供的属性值打开InputStream。

您可以像这样在XML布局中使用自定义视图:

<com.your.package.Loading 
    android:id="@+id/y_view1"
    ... />

但是您不能使用自己的构造函数,必须使用此答案中所示的构造函数。

因此,您必须通过代码和手动设置InputStream来访问“加载视图”:

Loading yourView = (Loading) findViewById(R.id.yourLoadingView);
yourView.setInputStream();

在您的Loading类中具有此setter方法的位置:

public void setInputStream(InputStream inputStream){
    movie = Movie.decodeStream(inputStream);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM