我尝试创建一个类似以下的应用程序:
那就是它。我是Android应用开发的新手,我一直处理触摸事件。谢谢你的帮助。以下是我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView img = (ImageView) findViewById(R.id.img);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
img.setOnTouchListener(new View.OnTouchListener(){
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
img.setImageResource(R.drawable.salmoon);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
img.setImageResource(R.drawable.lobster);
break;
}
return true;
}
});
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img"
android:src="@drawable/lobster"
android:layout_gravity="center" />
</RelativeLayout>
新代码(7月27日&#39; 16):
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img"
android:src="@drawable/pic"
android:clickable="true"
android:layout_gravity="center" />
</RelativeLayout>
pic.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/lobster" android:state_pressed="true"></item>
<item android:drawable="@drawable/salmoon"></item>
</selector>