基本上我有一个 TextView 需要从右侧移动到另一侧(我正在为不同的项目测试一些东西)。相反,一切都是静止的。没有执行任何操作。
另一件事需要指出:如果我删除 if 语句(这在我的情况下是必要的),那么一切都会正常工作。我认为条件是假的,所以我加了一个else语句。同样的事情发生了——什么也没有。我测试了这个条件是否为假——它是真的。所以 if 语句中的代码应该已经被执行了。
一切对我来说似乎都是合乎逻辑的,但我可能是错的。你可以帮帮我吗?我能改变什么?您对我的问题有不同的方法吗?谢谢!
P.S:问题不在于 TextView 的动画。问题是时间延迟。
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#000000"
android:text="0"
android:textColor="#000000" />
</RelativeLayout>
Java:
package com.nicksoft.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
int ind = -1;
private Handler h = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r.run();
}
private Runnable r = new Runnable() {
@Override
public void run() {
if(findViewById(R.id.textView).getX()>0) {
findViewById(R.id.textView).setTranslationX(ind);
ind--;
h.postDelayed(r,5);
}
}
};
}
最佳答案
没有任何效果,因为 getX
返回 0。在 onCreate
内舞台View
没有真正的坐标,因为布局尚未构建并且 getX
返回默认值 0 和 postDelayed
没有被调用。您调用r.run();
太早了。
You should wait until layout stage is finished.所有 View 都会获得它们的坐标。然后getX
将会返回一些有意义的东西并且你的代码将会工作。
如果您不 100% 需要使用此类自定义方法来实现“动画”,请使用默认平台方式,例如PropertyAnimator
关于java - 我有一个涉及 Android 中的 Handle.postDelay 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047078/