本文介绍了拖动图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着做一些应用程序,它具有当用户移动图像到某一个地方解开......但问题是,当用户触摸别处,除了图像,它仍然试图将它给这个错误:java.lang.ClassCastException:android.widget.AbsoluteLayout $的LayoutParams
I'm try to do some app which has to unlock when user moved image to a certain place... But the problem is when the user touch somewhere else except the image, it still tries to move and it gives this error: java.lang.ClassCastException: android.widget.AbsoluteLayout$LayoutParams
下面是我的codeS:
Here's my codes:
公共类主要活动扩展{
private View selected_item;
private int offset_x = 0;
private int offset_y = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ViewGroup vg = (ViewGroup) findViewById(R.id.lout);
vg.setOnTouchListener(new View.OnTouchListener() {
@SuppressWarnings("deprecation")
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX() - offset_x;
int y = (int) event.getY() - offset_y;
Log.e("SONUC", "SONUC1: " + x + ", " + y);
int w = getWindowManager().getDefaultDisplay().getWidth() - 25;
int h = getWindowManager().getDefaultDisplay().getHeight() - 25;
if (x > w)
x = w;
if (y > h)
y = h;
Log.e("SONUC", "SONUC2: " + x + ", " + y);
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT));
lp.x = x;
lp.y = y;
Log.e("SONUC", "SONUC3: " + lp);
selected_item.setLayoutParams(lp);
break;
case MotionEvent.ACTION_UP:
offset_x = (int) event.getX() - offset_x;
offset_y = (int) event.getY() - offset_y;
Log.e("SONUC", "SONUC5: " + offset_x + ", " + offset_y);
selected_item = v;
if (offset_x < 220 && offset_x > 150 && offset_y < 330 && offset_y > 300)
startActivity(new Intent("com.yahya.GeneralTraining.UNLOCKED"));
break;
default:
break;
}
return true;
}
});
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
offset_x = (int) event.getX();
offset_y = (int) event.getY();
Log.e("SONUC", "SONUC4: " + offset_x + ", " + offset_y);
selected_item = v;
break;
default:
break;
}
return false;
}
});
}
}
推荐答案
您可以提供的onTouchListener一个检查的ViewGroup,以确认该图像被点击开始。
You can provide a check in the onTouchListener for viewgroup to confirm that the image is clicked initially.
vg.setOnTouchListener(new View.OnTouchListener() {
@SuppressWarnings("deprecation")
public boolean onTouch(View v, MotionEvent event) {
if(selected_item.getId() == R.id.image){
switch (event.getActionMasked()) {
//your code
}
}
}
return true;
}
});
这篇关于拖动图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!