我试图让我的TextField在屏幕上移动。我希望能够将其拖动到屏幕上的新位置。我已经挣扎了好几天了,我真的无法想象这个...... 这就是我到目前为止所做的:
InputProcessor drag = new InputAdapter() {
@Override
public boolean touchDown(int screenX, int screenY, int pointer,
int button) {
// TODO Auto-generated method stub
return super.touchDown(screenX, screenY, pointer, button);
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer,
int button) {
int x = Gdx.input.getX();
int y = Gdx.input.getY();
textField.setPosition(x, y);
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return super.touchDragged(screenX, screenY, pointer);
}
};
game.inputMultiplexer = new InputMultiplexer();
game.inputMultiplexer.addProcessor(stage);
game.inputMultiplexer.addProcessor(stagePurc);
game.inputMultiplexer.addProcessor(stageText);
game.inputMultiplexer.addProcessor(drag);
Gdx.input.setInputProcessor(game.inputMultiplexer);
这是文本字段:
final TextField textField = new TextField(prefs.getString("textField", "Enter name:"), textstyle);
textField.setX(textX);
textField.setY(textY);
textField.setMaxLength(20);
textField.setWidth(textWidth);
textField.setHeight(textHeight);
答案 0 :(得分:0)
将TextView放在LinearLayout中:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:clipChildren="false"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@color/text_color"
android:textSize="16sp" />
</LinearLayout>
然后设置一个触控侦听器:
txt.setOnTouchListener(new View.OnTouchListener() {
int initialX = 0;
int initialY = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
initialX = (int) event.getX();
initialY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int currentX = (int) event.getX();
int currentY = (int) event.getY();
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) txt.getLayoutParams();
int left = lp.leftMargin + (currentX - initialX);
int top = lp.topMargin + (currentY - initialY);
int right = lp.rightMargin - (currentX - initialX);
int bottom = lp.bottomMargin - (currentY - initialY);
lp.rightMargin = right;
lp.leftMargin = left;
lp.bottomMargin = bottom;
lp.topMargin = top;
txt.setLayoutParams(lp);
break;
default:
break;
}
return true;
}
});
效果很好。我从这里得到了这段代码:How to make the TextView drag in LinearLayout smooth, in android?