我尝试做一些必须在用户将图像移动到某个地方时解锁的应用程序...但问题是当用户触摸除图像以外的其他地方时,它仍会尝试移动并且它会出现此错误:java.lang.ClassCastException:android.widget.AbsoluteLayout $ LayoutParams
这是我的代码:
public class Main扩展Activity {
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;
}
});
}
}
答案 0 :(得分:2)
您可以在onTouchListener中为viewgroup提供检查,以确认最初是否单击了该图像。
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;
}
});
答案 1 :(得分:0)
第一件事不是从容器中创建LayoutParam
刚刚获取LayoutParam
对象的新对象,如图像或布局
假设获得ImageView
然后
LayoutParam lp = imageView.getLayoutParam();
lp.width = newWidth;
lp.height = newHeight;
现在更改尺寸并在imageView.setLayoutParam()
imageView.setLayoutParam(lp);
另一件事是你还设置了ViewGroup
的触摸监听器,只为ImageView
设置了未设置ViewGroup
的触摸监听器,并且在触摸监听器实现中返回true表示触控监听器已实施