我有一个MainActivity,我的大部分代码都是在这里编写的。我在activity_main.xml中有一个imageview,我将其设置为Mainactivity中的默认图像。
我的另一个文件“OnSwipeTouchListener”正在侦听滑动和双击事件,我已经编写了代码来更改用户双击时图像视图的图像,但我的代码不起作用,也没有出现任何错误。 (我正在使用Layoutinflater来扩展activity_main文件。)
这是OnSwipeTouchListener
package com.backspace.memebook;
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class OnSwipeTouchListener extends MainActivity implements OnTouchListener {
private final GestureDetector gestureDetector;
public Context ctx;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
this.ctx = ctx;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
System.out.println("double tap");
LayoutInflater mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.activity_main, null);
ImageView isFunny = (ImageView) view.findViewById(R.id.isFunny);
isFunny.setImageResource(R.drawable.funny);
return super.onDoubleTap(e);
}
}
}
Mainactivity没有太多代码,它只是设置了一个显示正常的imageview的默认图像,但是当我尝试使用另一个类更改它时,它不会改变。
ANybody有任何线索?
答案 0 :(得分:1)
在评论中写作时,您需要在活动中夸大视图。这样的事情应该有效(未经测试)
public class MainActivity extends Activity {
public ImageView iv = null;
public void onCreate(....) {
setContentView( ... );
iv = findViewById(....);
}
public class OnSwipeTouchListener extends MainActivity implements OnTouchListener {
//public ImageView iv from MainActivity
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDoubleTap(MotionEvent e) {
iv.setImageResource(R.drawable.funny); //iv is accessable, you may also use a constructor to pass the reference.
return super.onDoubleTap(e);
}
}
}
您可能希望将引用传递给GestureListener构造函数内的ImageView,而不是从OnSwipeTouchListener访问数据
答案 1 :(得分:0)
您在活动中不存在的视图中再次展开您的布局。您应该在setContentView之后在onCreate中使用findViewById并在onDoubleTap()中更改ImageView背景。