[英]How to redraw View in Android
我有一個自定義視圖,在其中播放GIF實際上是一個加載程序。 每當我進行后台工作時,我都會將“ GIF視圖”可見性設置為“開”,並在完成工作時將其可見性設置為“消失”。 以下是我的自定義GifLoader Java代碼。
public class GifLoader extends View {
private InputStream gifInputStream;
private Movie gifMovie;
private int movieWidth, movieHeight;
private long movieDuration;
private long mMovieStart;
public GifLoader(Context context) {
super(context);
init(context);
}
public GifLoader(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public GifLoader(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context){
setFocusable(true);
gifInputStream = context.getResources()
.openRawResource(R.drawable.loading);
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
@Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
setMeasuredDimension(movieWidth, movieHeight);
}
public int getMovieWidth(){
return movieWidth;
}
public int getMovieHeight(){
return movieHeight;
}
public long getMovieDuration(){
return movieDuration;
}
@Override
protected void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (gifMovie != null) {
int dur = gifMovie.duration();
if (dur == 0) {
dur = 100;
}
int relTime = (int)((now - mMovieStart) % dur);
gifMovie.setTime(relTime);
gifMovie.draw(canvas, 0, 0);
invalidate();
}
}
}
這是我的XML代碼。
<yas.life.utils.GifLoader
android:visibility="gone"
android:layout_centerInParent="true"
android:id="@+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
現在的問題是,每當我將其可見性設置為可見時,GIFview就會在其可見性消失的情況下運行,而不是從其初始狀態開始運行。 我想做的是GIFloader應該從其初始狀態開始。 無論何時,只要我將可見性設置為visible或任何其他方式來實現此目的,是否都需要重新啟動此Custom GIFview。
嘗試通過調用invalidate()
重繪視圖
https://developer.android.com/reference/android/view/View.html#invalidate()
我認為Movie.setTime(0)
可以解決您的問題。
您可以在onDraw()
查看視圖的可見性狀態,並在視圖消失時將gif時間設置為0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.