【问题标题】:I want to play gif animation on touch event我想在触摸事件上播放 gif 动画
【发布时间】:2013-08-06 05:24:38
【问题描述】:
package com.example.gifsample;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

//@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GIFWebView view = new GIFWebView
            (this, "file:///android_asset/imageedit_ball.gif");

        setContentView(view); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

.

package com.example.gifsample;

import android.content.Context;
import android.webkit.WebView;

public class GIFWebView extends WebView {
    public GIFWebView(Context context, String path) {
        super(context);
        loadUrl(path);
        // TODO Auto-generated constructor stub
    }
}

现在我希望每当我触摸我的屏幕时在触摸事件上播放它,并且它应该在它的一个循环完成后停止。 当动画已经播放时,我不想再次播放动画。动画应该完成循环,然后可以在触摸事件上再次播放。

【问题讨论】:

  • 如果gif 本身在循环——你无法阻止它,它是内置在其中的。
  • 不,我正在编辑 gif。所以它只是一个循环 gif

标签: android animated-gif


【解决方案1】:

如果你想听MOTION_EVENTSonTouch() 方法)使用此代码并将其粘贴到MainActivity

@Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getAction()){
    case MotionEvent.ACTION_DOWN:
    // You can also put any code here, it will be caught when you touch the screen
    break;
    // This event here is triggered when you lift your finger from the screen, when touching it
    case MotionEvent.ACTION_UP:

    GIFWebView view = new GIFWebView
        (this, "file:///android_asset/imageedit_ball.gif");

    setContentView(view);

    break;
    }
    return true;
}

如果您的gif 文件只循环一次,它将显示为这样。

因为您正在实例化一个扩展 WebView 的类。这些类不会拦截onTouch 事件。只有 Activity 类可以。

这里有一个关于播放 gif 文件的好消息 - LINK 和 google.cod 中的一个不错的项目,您可以使用 - LINK

【讨论】:

  • 但是这样做的问题是它使用 setcontentview() 占据了整个屏幕。如果可能的话,如何将此视图转换为 imageview 或 imagebutton 使 gif 动画可以在布局内与所有其他东西一起使用..
  • 我已经尝试过这段代码,但每次都会创建一个新的 GIFView 对象,即视图。我一开始已经创建了它。gif 正在播放 onload 事件,但之后它被停止,然后在触摸事件中它不再被播放。我什至尝试创建 GIFView 的全局对象,但我找不到解决方案。
  • 是的,这是因为您正在实例化一个扩展 WebView 的类。这些类不会拦截onTouch 事件。只有Activity 类可以。
  • 我编辑了问题,有三种(或更多)方法可以加载gif 文件:将其拆分为帧并为其设置动画,使用WebView(您的方法在这里)并在里面使用它VideoView。当您打开文件时,只有您的方法不会拦截屏幕上的触摸,因为处理它的类正在扩展WebView
猜你喜欢
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多