Android图片在界面任意拖动代码
时间: 2024-02-27 12:55:52 浏览: 39
要实现在 Android 界面中任意拖动图片的功能,可以使用 onTouchEvent() 方法来实现。以下是一个简单的代码示例:
首先,在 layout.xml 文件中添加一个 ImageView:
```xml
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image" />
```
然后,在 Activity 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private float startX, startY;
private int lastAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
startX = imageView.getX() - event.getRawX();
startY = imageView.getY() - event.getRawY();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
imageView.setX(event.getRawX() + startX);
imageView.setY(event.getRawY() + startY);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
if (lastAction == MotionEvent.ACTION_DOWN)
Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
break;
default:
return false;
}
return true;
}
});
}
}
```
在代码中,我们使用了 setOnTouchListener() 方法来监听 ImageView 的触摸事件。在触摸事件中,我们使用了 switch-case 语句来处理不同的事件类型。在 ACTION_DOWN 事件中,我们记录了起始的触摸点位置,并设置 lastAction 变量为 ACTION_DOWN。在 ACTION_MOVE 事件中,我们计算了手指移动的距离,并将 ImageView 的位置设置为手指的当前位置加上起始的偏移量。在 ACTION_UP 事件中,我们检查 lastAction 变量是否为 ACTION_DOWN,如果是,就认为用户单击了 ImageView。
这样,就可以实现在 Android 界面中任意拖动图片的功能了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)