gpt4 book ai didi

android - 以编程方式设置 View 的位置

转载 作者:行者123 更新时间:2023-11-30 05:09:26 25 4
gpt4 key购买 nike

我有一个 float 操作按钮,带有一个 touchListener 可以在屏幕上移动它。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">

<android.support.design.widget.FloatingActionButton
android:id="@+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:color/holo_blue_bright"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

以及移动它的代码:

floatingActionButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
positionX = view.getX() - event.getRawX();
positionY = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
view.animate()
.x(event.getRawX() + positionX)
.y(event.getRawY() + positionY)
.setDuration(0)
.start();
break;
case MotionEvent.ACTION_UP:
SharedPreferences sharedPreferences = getSharedPreferences("stored_position", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putFloat("pos_x", positionX).apply();
editor.putFloat("pos_y", positionY).apply();
break;
}
return true;
}
});

一切正常,但是我在 onCreate 中设置存储的 X 和 Y 值时面临挑战, View 仍处于其原始位置:(这是我尝试做的)

SharedPreferences sharedPreferences = getSharedPreferences("stored_position", Context.MODE_PRIVATE);
Float savedPositionX = sharedPreferences.getFloat("pos_x", 0);
Float savedPositionY = sharedPreferences.getFloat("pos_y", 0);

floatingActionButton = findViewById(R.id.floatingActionButton);
if (savedPositionX != 0 && savedPositionY != 0) {
floatingActionButton.setX(savedPositionX);
floatingActionButton.setY(savedPositionY);
}

//setTranslation has also not worked

我怎样才能达到预期的效果?

最佳答案

您可以使用相同的调用来定位 View (FAB 按钮)。

    SharedPreferences sharedPreferences = getSharedPreferences("stored_position", Context.MODE_PRIVATE);
Float savedPositionX = sharedPreferences.getFloat("pos_x", 0);
Float savedPositionY = sharedPreferences.getFloat("pos_y", 0);

floatingActionButton = findViewById(R.id.floatingActionButton);
if (savedPositionX != 0 && savedPositionY != 0) {
//this is working i have tested
floatingActionButton.animate()
.x(savedPositionX)
.y(savedPositionY)
.setDuration(0)
.start()
}

但是 View 的位置不会相同,纵向和横向的宽/高比例会不同。

关于android - 以编程方式设置 View 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com