GitHub download address: https://github.com/koral--/android-gif-drawable-eclipse-sample (a routine of eclipse, please Baidu if you need others)
Click Download ZIP to download:
put all the folders under the libs folder Copy it to the project directory libs (eg: .\Dp Notes\libs), copy the lp folder under src to the project directory src (eg: .\Dp Notes\src).
Right-click on the ADT project name to refresh:
Well, a bunch of errors were reported. It should be that the library has been updated. The main reason for the error is that the SDK version of ADT is too low. The solution is of course to update the SDK (update is too slow? Forget it, no updated), each file is corrected.
First of all, import android.support.annotation.x reports an error:
Baidu, download support-annotations-23.0.1.jar and put it under libs, address: http://download.csdn.net/download/lvshaorong/9399501, CSDN points-free .
Then, something like final ConcurrentLinkedQueue<AnimationListener> mListeners = new ConcurrentLinkedQueue<AnimationListener>();
Similar to catch (Exception ignored)
Similar to
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public GifImageView(Context context, AttributeSet attrs, int defStyle, int defStyleRes) {
// super(context, attrs, defStyle, defStyleRes);
/ / postInit(GifViewUtils.initImageView(this, attrs, defStyle, defStyleRes));
// }
Finally, bold comments that are wrong, so far.
Simple display test, the last addition to Activity_main.xml:
<pl.droidsonroids.gif.GifImageView android:id="@+id/giv_demo" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/gif_smaple"/>
gif_smaple is a GIF animation file, run:
Note: This is a .gif animation, ctrl click on the picture to view
the ADT tool is really going to be eliminated, the last time it is used.
How does the code add a GifImageView and display a moving image? In fact, just like the control that comes with Android, you can set a new property, which is directly implemented in the ListView Item in the previous section:
if("gif".equals(data.type)){//To display GIF if(holder.tv_gifctrl!=null){//GIF control is removed first holder.rl_data.removeView(holder.tv_gifctrl); } if(holder.giv_data!=null){//GIF display first removed holder.giv_data.setVisibility(View.GONE); } RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); holder.tv_gifctrl=new TextView(activity);//Generate GIF control holder.tv_gifctrl.setText("GIF");//Set some TextView properties holder.tv_gifctrl.setGravity(Gravity.CENTER_HORIZONTAL); holder.tv_gifctrl.setTextColor(activity.getResources().getColor(R.color.white_dark)); holder.tv_gifctrl.setTextSize(TypedValue.COMPLEX_UNIT_PX,activity.getResources().getDimension(R.dimen.text_level1)); int padding=(int)activity.getResources().getDimension(R.dimen.padding_n); GradientDrawable gd = new GradientDrawable(); gd.setColor(activity.getResources().getColor(R.color.black_normal_88)); gd.setCornerRadius(padding); holder.tv_gifctrl.setBackground(gd);//Set the background of rounded corners holder.tv_gifctrl.setPadding(padding,padding,padding,padding); lp1.addRule(RelativeLayout.CENTER_IN_PARENT); holder.tv_gifctrl.setLayoutParams (lp1); holder.tv_gifctrl.setTag(tagctrlgif);//Set TAG holder.rl_data.addView(holder.tv_gifctrl);//Add to layout OnClickListener listener=new OnClickListener() {//Click listener @Override public void onClick(View v) { // TODO Auto-generated method stub v.setOnClickListener(null);//Clear the listener v.findViewWithTag(tagctrlgif).setVisibility(View.GONE);//Find GIF control through TAG, hide if(holder.giv_data!=null){ //GIF display first remove holder.rl_data.removeView(holder.giv_data); } RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); //Generate GIF display holder.giv_data=new GifImageView(activity); holder.giv_data.setLayoutParams (lp); holder.giv_data.setTag (tagdata); // 设置 TAG holder.rl_data.addView(holder.giv_data);//Add to the layout //Load GIF image resource GifDrawable drawable=gifload.loadImage(viewparent,tagdata,data.dataurl,glcallback); if(drawable!=null){//Already loaded drawable.start();//Start playing, set holder.giv_data.setBackground(drawable); } else{//Add a progress bar RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); holder.pb_load=new ProgressBar(activity,null,android.R.attr.progressBarStyleSmall); lp1.addRule(RelativeLayout.CENTER_IN_PARENT); holder.pb_load.setLayoutParams(lp1); holder.pb_load.setTag(tagloadgif); holder.rl_data.addView(holder.pb_load); } } }; holder.rl_data.setOnClickListener(listener);//Set the listener }
A GIF loaded listener similar to when the image is loaded:
private GifLoadCallback glcallback=new GifLoadCallback() { @SuppressLint("NewApi") @Override public void onSuccess(GifDrawable drawable, int tag, View viewParent) { // TODO Auto-generated method stub if(drawable!=null){ //Find the GIF display by TAG GifImageView giv_data=(GifImageView)viewParent.findViewWithTag(tag); if(giv_data!=null){//Find, set display // LayoutParams lp=rl_data.getLayoutParams(); // lp.height=itemWidth*drawable.getMinimumHeight()/drawable.getMinimumWidth(); // rl_data.setLayoutParams (lp); drawable.start(); giv_data.setBackground(drawable); viewParent.findViewWithTag(tag+1).setVisibility(View.GONE);//GIF control hidden viewParent.findViewWithTag(tag-1).setVisibility(View.GONE);//GIF loading progress bar is hidden } } } };
Attach the class loaded by GifDrawable, similar to the loading of image Drawable:
public class GifLoad { private Context context; private Map<String, GifDrawable> imageMap; private ThreadPoolExecutor executor = null; BlockingQueue<Runnable> queue =null; private String path=Environment.getExternalStorageDirectory()+"/Dp Notes/Cache/GifImage"; private int threadMaxNum=Runtime.getRuntime().availableProcessors()>1?Runtime.getRuntime().availableProcessors():2; private int cacheMaxNum=1; @SuppressLint("NewApi") public GifLoad(Context context){ this.context=context; imageMap=new LinkedHashMap<String, GifDrawable>(); queue =new ArrayBlockingQueue<Runnable>(this.threadMaxNum); executor=new ThreadPoolExecutor(this.threadMaxNum,this.threadMaxNum,1,TimeUnit.MINUTES,queue,new ThreadPoolExecutor.CallerRunsPolicy()); // File dir=new File(this.path); // if(!dir.exists()){ // dir.mkdirs(); // } } public void setcacheMaxNum(int maxNum){ this.cacheMaxNum=maxNum; } public GifDrawable loadImage(final View viewParent,final int viewTag,final String imageUrl,final GifLoadCallback callback){ if (imageMap.containsKey(imageUrl)) { GifDrawable drawable=imageMap.get(imageUrl); return drawable; } // int index=imageUrl.lastIndexOf("/"); // index=index>=0?index:0; // String filename=imageUrl.substring(index); // final String filepath=path+filename+".0"; // // final File mf=new File(filepath); // if(mf.exists()){ // //File read to be added // if(draw!=null){ // imageMap.put(imageUrl,draw); // chackMapSize(); // return draw; // } // } imageMap.put(imageUrl,null); final Handler handler = new Handler () { @SuppressLint("HandlerLeak") public void handleMessage(Message message) { if(callback!=null){ if(message.what==1){ callback.onSuccess((GifDrawable)message.obj,viewTag,viewParent); } } } }; executor.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub URL url = null; InputStream inputStream = null; try { url = new URL(imageUrl); inputStream = url.openStream(); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[512]; int rc = 0; try { while ((rc = inputStream.read(buff, 0, 512)) > 0) { swapStream.write(buff, 0, rc); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace (); } try { swapStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace (); } GifDrawable drawable=null; if(swapStream.size()>0){ drawable=new GifDrawable(swapStream.toByteArray()); Message message=handler.obtainMessage(1,drawable); handler.sendMessage(message); imageMap.put(imageUrl,drawable); chackMapSize(); } else{ Message message=handler.obtainMessage(1,drawable); handler.sendMessage(message); imageMap.remove(imageUrl); } // if(drawable!=null){ // FileOutputStream fout=null; // try { // if(!mf.exists()){ // mf.createNewFile(); // } // fout=new FileOutputStream(mf); // fout.write(swapStream.toByteArray()); // fout.flush(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace (); // } finally { // try { // if(fout!=null){ // fout.close(); // } // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace (); // } // } // } } catch (Exception e) { e.printStackTrace (); } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException e) { e.printStackTrace (); } } } }); return null; } private void chackMapSize(){ if(imageMap.size()>cacheMaxNum){ for(Entry<String, GifDrawable> m:imageMap.entrySet()){ imageMap.remove(m.getKey()); break; } } } public interface GifLoadCallback { public void onSuccess(GifDrawable drawable,int tag,View viewParent); } }
Run and see:
Note: This is a .gif animation, ctrl click on the picture to view
Don't be discouraged - 2017/06/07