我是 Android 新手,但对 c# 和 c++ 有经验。
我只是想在按下按钮时显示。我搜索并发现,onClick 事件无法做到这一点,因此我使用了 onTouch 事件。
对于第一个按钮,它很好并且有效。然后我添加了第二个和第三个,但现在应用程序在我执行时崩溃了。
如果我删除带有事件的第二个和第三个按钮,应用程序仍然会崩溃。在我删除第一个 Button 和他的事件之前,应用程序停止崩溃。
这里是我的 main.code 和 layout-xml 的代码:
package com.android.kurve;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
boolean left=false;
boolean right=false;
final Button buttonLeft = (Button) findViewById(R.id.button1);
final Button buttonRight = (Button) findViewById(R.id.button2);
final Button buttonMove = (Button) findViewById(R.id.button3);
final TextView text = (TextView) findViewById(R.id.textView1);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonLeft.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
left=true;
text.setText("left");
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
left=false;
}
return true;
}
});
buttonRight.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
right=true;
text.setText("right");
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
right=false;
}
return true;
}
});
buttonMove.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
text.setText("move");
return true;
}
});
}
}
这里的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="28dp"
android:layout_marginTop="207dp"
android:text="Left" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/button1"
android:layout_marginRight="31dp"
android:text="Right" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="24dp"
android:layout_toLeftOf="@+id/textView1"
android:text="Move" />
</RelativeLayout>
谢谢您的帮助。