阅读APP源码,了解Android studio触摸事件,切换图片
阅读APP源码,了解Android studio触摸事件,切换图片
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity10">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:id="@+id/image"/>
</LinearLayout>
java代码:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity10 extends AppCompatActivity {
// 定义数组,用来访问图片资源
private int[] imgs = {R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four};
private ImageView image;
// 触摸开始和结束位置值
private float startx=0.0f,endx=0.0f;
// 图片默认索引值
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main10);
image = findViewById(R.id.image);
// 初始化第一张图片
image.setImageResource(imgs[count]);
// 给图片设置触摸事件
image.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// 获取水平方向的值
float x = motionEvent.getX();
// 获取触摸的初始位置
if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
startx = x;
}
// 获取触摸的结束位置
if(motionEvent.getAction()==motionEvent.ACTION_UP){
endx = x;
// 判断滑动的距离是否超过100
if(Math.abs(startx-endx) > 100){
if(startx > endx){ // 向左滑动
// 判断图片索引是否等于3
if (count == 3){
Toast.makeText(MainActivity10.this,"已经是最后一张啦",Toast.LENGTH_SHORT).show();
} else {
// 图片索引+1
image.setImageResource(imgs[++count]);
}
} else { // 向右滑动
// 判断图片索引是否等于0
if (count == 0){
Toast.makeText(MainActivity10.this,"已经是第一张啦",Toast.LENGTH_SHORT).show();
} else {
// 图片索引-1
image.setImageResource(imgs[--count]);
}
}
}
}
return true;
}
});
}
}
以上就是 阅读APP源码,了解Android studio触摸事件,切换图片,更多内容欢迎关注之后的文章