我在这里有一些奇怪的行为(无论如何对我来说看起来很奇怪)。
我有两个按钮,向左/向右拖动一个也会移动另一个。这工作正常,直到我使用 setText 更新 TextView 并详细说明它所在的事件。如果下面的 tv.setText 行未注释,它似乎导致按钮被设置回其原始位置。
如果我正在做一些明显愚蠢的事情并且有人可以让我知道,我将不胜感激。
谢谢。
代码在这里:
package com.kk.moveit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class MoveIt extends Activity {
Button b1,b2;
TextView tv;
int b1X;
int wndwX;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move_it);
b1 = (Button)findViewById(R.id.b1);
b2 = (Button)findViewById(R.id.b2);
tv = (TextView)findViewById(R.id.tv);
b1.setOnTouchListener( new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// the view is pressed
b1X = (int) event.getX();
wndwX = (int) event.getRawX();
// tv.setText("ACTION_DOWN");
return false;
//break;
case MotionEvent.ACTION_MOVE:
// a movement is applied to the view
int l0 = view.getLeft();
int l = (int) event.getRawX() - b1X;
int r = l + view.getWidth();
view.layout(l, view.getTop(), r, view.getBottom());
move(b2,l-l0);
// tv.setText("ACTION_MOVE");
return true;
case MotionEvent.ACTION_UP:
// tv.setText("ACTION_UP");
// the view is released
return true; // finished with this event
case (MotionEvent.ACTION_CANCEL):
// something happened and the
// action was not completed
return true; // finished with this event
case (MotionEvent.ACTION_OUTSIDE):
// action happened outside the bounds
// of the view
return true; // finished with this event
}
return false;
}
});
}
private void move(View v, int l) {
int l0 = v.getLeft();
v.layout(l+l0, v.getTop(), l+l0+v.getWidth(), v.getBottom());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_move_it, menu);
return true;
}
}
和这里的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MoveIt" />