加载中动画(gif)
大家都知道,Android開發模擬器為了節省內存,一般不支持直接顯示gif圖片,即使你強制設置了,也只會顯示圖片的第一幀??吹骄W上也有許多的方法,來實現此功能,可都比較的繁瑣,需要修改android源代碼來實現或者用gif解析器來實現。在此文章中,這里教大家一種比較簡潔的一個方法,你可以把這個類當做是一種工具類。用的時候,直接搬到程序里面,更改下圖片的資源,就可以非常輕松的顯示gif圖片了。
?
步驟1:看一下這個工具類的實例代碼:MyGifView.java
| import?android.content.Context; import?android.graphics.Canvas; import?android.graphics.Movie; import?android.util.AttributeSet; import?android.view.View; ? public?class?MyGifView?extends?View{ private?long?movieStart; private?Movie?movie; ????//此處必須重寫該構造方法 public?MyGifView(Context?context,AttributeSet?attributeSet)?{ super(context,attributeSet); //以文件流(InputStream)讀取進gif圖片資源 movie=Movie.decodeStream(getResources().openRawResource(R.drawable.keyboard)); } ? @Override protected?void?onDraw(Canvas?canvas)?{ long?curTime=android.os.SystemClock.uptimeMillis(); //第一次播放 if?(movieStart?==?0)?{ movieStart?=?curTime; } if?(movie?!=?null)?{ int?duraction?=?movie.duration(); int?relTime?=?(int)?((curTime-movieStart)%duraction); movie.setTime(relTime); movie.draw(canvas,?0,?0); //強制重繪 invalidate(); } super.onDraw(canvas); } } |
此工具類中,只做了2件事情。1,構造方法;2,重寫了onDraw()方法。大家以后用的話,只需拷貝此類到你的工程下即可起作用。
步驟2:布局文件代碼?activity_main.xml
| <LinearLayout?xmlns:android="http://schemas.android.com/apk/res/android" ????xmlns:tools="http://schemas.android.com/tools" ????android:layout_width="match_parent" ????android:layout_height="match_parent"?> ? ????<TextView? ???????android:text="====Gif圖片測試布局====" ????????android:layout_height="wrap_content" ???????android:layout_width="wrap_content" ???????/> ???? ?????<com.example.showgifimage.MyGifView? ???????android:id="@+id/iv" ???????android:layout_height="wrap_content" ???????android:layout_width="wrap_content" ???????android:layout_margin="20dp" ???????/>? ??? </LinearLayout> |
布局文件中,注意的是:標簽的設置?<com.example.showgifimage.MyGifView/>.
格式:包名+.類名
?
步驟3:主activity中調用
| public?class?MainActivity?extends?Activity?{ ????@Override ????public?void?onCreate(Bundle?savedInstanceState)?{ ????????super.onCreate(savedInstanceState); ????????setContentView(R.layout.activity_main); ????} } |
????就這么輕松的把Gif圖片顯示了~~
總結
以上是生活随笔為你收集整理的加载中动画(gif)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微博html5版不能登录界面,爬取微博信
- 下一篇: wordpress 根据文章ID获取分类