android 拖动一个控件在另一个控件(layout)上,并固定位置在几个位置显示。OnTouchListener TranslateAnimation

本文介绍如何实现在Android应用中,通过OnTouchListener监听拖动一个按钮(SSS)在水平布局上,当松开手指时,按钮会通过TranslateAnimation动画自动移动并定位到最近的按钮旁边,确保SSS只存在于五个特定的显示位置。
摘要由CSDN通过智能技术生成

实现效果: 鼠标拖动btn SSS,SSS在水平的layout上移动。 当鼠标抬起 响应UP事件。SSS会自动移动到距离其最近的Btn上,与其重合。即SSS如图只存在五个固定的显示位置。

 

SSS响应setOnTouchListener事件。

在MotionEvent.ACTION_UP事件中,调用TranslateAnimation动画效果,将其从UP事件位置移动到最近的btn所在位置。

 

即在UP事件中,响应函数:

private void setPosition() {
            int positionPixel = (touchBtn.getLeft()+touchBtn.getRight())/2;
            int positionIndex = (positionPixel)/btn[1].getWidth();
            int toPosition = positionIndex*btn[1].getWidth()+touchBtn.getWidth()/2;       
            touchBtn.layout(positionIndex*btn[1].getWidth(), touchBtn.getTop(),positionIndex*btn[1].getWidth()+touchBtn.getWidth(),
                            touchBtn.getBottom());           
            MoveAction = new TranslateAnimation(positionPixel - toPosition,0,0,0);
            MoveAction.setDuration(500);
            touchBtn.startAnimation(MoveAction);
//            touchBtn.invalidate();           
        }

动画效果,将其移动到最近位置上

好的,以下是实现Android触摸点击屏幕隐藏控件再点击恢复显示的代码示例: XML布局文件: ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_centerInParent="true"/> </RelativeLayout> ``` Java代码: ```java public class MainActivity extends AppCompatActivity implements View.OnTouchListener { private RelativeLayout layout; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout = findViewById(R.id.layout); textView = findViewById(R.id.textView); layout.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (textView.getVisibility() == View.VISIBLE) { textView.setVisibility(View.INVISIBLE); } else { textView.setVisibility(View.VISIBLE); } return true; } return false; } } ``` 该代码与之前的代码示例相似,只是将RelativeLayout的点击事件改为了触摸事件,并且实现了View.OnTouchListener接口。当触摸事件为ACTION_DOWN时,判断TextView的可见性并设置其可见性的值。同时,返回true表示事件已经被处理,不再继续传递。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值