1

我有一个自定义视图:

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 布局中传递参数(上下文、输入流)?

4

3 回答 3

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

How can I pass the parameters 

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

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

<view class="Your_package.MainClass$Loading" />
于 2012-06-29T18:52:11.173 回答
0

简短的回答是你不能直接这样做。

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

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

What you need to do is implement the normal constructors from View. Define a custom attribute that declares the resource to use to create the InputStream in your constructor. The view system will give you the context automatically, you'd then need to open the InputStream based on the provided attribute value.

于 2012-06-29T18:55:20.363 回答
0

You can use a custom View in an XML-Layout like this:

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

But you cannot use your own constructor, you have to use the constructors as shown in this answer.

So you have to access your Loading View by code an set the InputStream manually:

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

where you have this setter method in your Loading class:

public void setInputStream(InputStream inputStream){
    movie = Movie.decodeStream(inputStream);
}
于 2012-06-29T19:02:21.093 回答