1

I have a custom view:

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();
    }

}

How can I use this view in XML layout? How can I pass the parameters (Context, InputStream) in XML layout?

3 Answers3

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

There is a form of the constructor that are called when the view is created from code and a 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

Error referencing an inner class View in layout/main.xml

<view class="Your_package.MainClass$Loading" />
Community
  • 1
  • 1
Dheeresh Singh
  • 15,446
  • 3
  • 35
  • 36
0

The short answer is you can't directly do that.

The long answer is that you can indirectly do that.

Add the view to the XML by its fully qualified name (as others have mentioned), then:

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.

nEx.Software
  • 6,474
  • 1
  • 23
  • 34
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);
}
Community
  • 1
  • 1
Floern
  • 31,495
  • 23
  • 98
  • 115