Loading class (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, 100, 100);
this.invalidate();
}
}
Activity onCreate method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream inputStream = null;
try {
inputStream = getAssets().open("loading.gif");
} catch(IOException e) {
e.printStackTrace();
}
Loading loading = new Loading(this, inputStream);
setContentView(loading);
}
I want to set the view in center of the device layout. Like in XML layout, that we can set android:layout_centerHorizontal=”true”. How can I do it?
You need to set LayoutParams for the View. What I would do is put your custom view in a container, for example a FrameLayout. Then, create your view and set the FrameLayout.LayoutParams for your View with gravity set to CENTER_HORIZONTAL. It’ll look something like this
You may want to configure the FrameLayout to get it to display how you want.
Here’s the documentation for the LayoutParams constructor I’d use: http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html#FrameLayout.LayoutParams%28int,%20int,%20int%29
It’s important to remember that each of the Views that extend ViewParent have their own LayoutParams class, so, for example, if you wanted to use a LinearLayout instead of a FrameLayout, you’d use LinearLayout.LayoutParams. Different types of Params have different constructor options, so you can play around with it and find which is best for you. Good luck.