你好为自闭症儿童制作一个应用程序(Android Studio)(灵感来自我的自闭症儿子)。在我的活动中,我有2个线性布局:顶部和底部。顶部是我的屏幕的3/4,有4个图像。底部是目标放置点,应该删除“Answer”或img。
我有一个4 img随机创建(通过databaseFP迭代)但现在我希望那些img在屏幕(顶部屏幕)内随机移动并将它们拖动到目标拖动框(底部屏幕)。四个img中只有一个是正确的“答案”,所以如果它的“不正确”,我希望这个img返回到它在屏幕内一直移动的位置,直到选择“正确”img到目标丢弃框。这就是全部......请帮助我,我已经阅读了很多,而不是特别喜欢它涉及onTouch / onDrag监听器,如果被拖动,img会回到位置。
到目前为止,我所做的只是让img移动(它保留了点击和拖动但是当它不正确时它会离开屏幕)请参阅下面的代码
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
int distance = 100; //the distance to move in pixels
int duration = 500; //the duration of the animation in ms
double direction = Math.random() * 2 * Math.PI;
int translationX = (int) (Math.cos(direction) * distance);
int translationY = (int) (Math.sin(direction) * distance);
int id2 = getResources().getIdentifier(myShuffledArray[0], "drawable", getPackageName());
image.setImageResource(id2);
image.animate().translationX(translationX - width).translationY(translationY - height).setDuration(duration).start();
我是新手,但这会帮助我的自闭症儿子,这是我大学的论文项目。
编辑这是我的ontouch / drag
public boolean onDrag(View v, DragEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==DragEvent.ACTION_DROP){
//we want to make sure it is dropped only to left and right parent view
View view = (View)event.getLocalState();
//if(v.getId() == R.id.left_view || v.getId() == R.id.right_view){
if(view.getId() == R.id.box_view1){
ViewGroup source = (ViewGroup) view.getParent();
source.removeView(view);
LinearLayout target = (LinearLayout) v;
target.addView(view);
}
//make view visible as we set visibility to invisible while starting drag
view.setVisibility(View.VISIBLE);
}
return true;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(null, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
}
return false;
}
答案 0 :(得分:0)
我在本网站上发现了解决方案 https://blahti.wordpress.com/2011/01/17/moving-views-part-2/ 查看那些想要了解更多关于视图和拖放的人