我似乎无法在google或SO上找到我的问题的答案,所以让我试着解释一下。
我有一个主要活动,它创建一个自定义片段。然后,此CustomFragment包含几个自定义“扩展”按钮(视图),其中应用了一个ObjectAnimator。
即使isRunning()返回true,ObjectAnimator也不会在主线程上更新(我假设)。 ObjectAnimator在CustomFragment内部工作得很好,但是当在Extended Button类中使用它时,它会失败。
我认为我需要使用runOnUiThread()或其他方式让它在正确的线程上运行,但我找不到一个好的解决方案。
这是一些伪代码:
public class TestButton extends Button{
private AnimatorSet as;
public TestButton(Context context, AttributeSet attrs){
super(context, attrs);
init();
}
private void init(){
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0.2f, 1.0f);
as = new AnimatorSet();
as.play(alphaAnimator);
as.setDuration(1000);
}
public void startAnimation(){
as.start();
//tried adding invalidate(); here but that didn't seem to fix it either
}
}
public class CustomFragment extends android.support.v4.app.Fragment implements Runnable {
private View root;
private ArrayList<TestButton> buttons;
public View onCreateView(LayoutInflater inflater, ViewGroup container, bundle SavedInstanceState){
root = inflater.inflate(R.layout.fraglayout, container, false);
initButtons();
return view;
}
private void initButtons(){
buttons = new ArrayList<TestButton>();
//Code here to initialize and find the buttons in the layout, this works properly
//so I won't define it here because it is long, the list does contain its members
//
}
private void startTest(View view){
//An actual "Button" controls this, and is called properly
//THE FOLLOWING WORKS PERFECTLY FINE
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 0.2f, 1.0f);
alphaAnimator.setDuration(1000);
alphaAnimator.start();
//THIS DOES NOT WORK AT ALL, JUST CHANGES THE VIEW ONCE BUT ANIMATION DOESNT 'RUN'
for(TestButton b : buttons){
b.startAnimation();
}
}
@Override
public void run(){
root.postDelayed(this,1000);
}
}
它必须是线程化的东西,但我不确定它可能是什么。
感谢任何帮助,
由于
---编辑--- 好吧,所以我只是搞乱了线程并添加了一个简单的布尔值来测试是否在Fragment的Run()函数中启动动画。它确实适用于动画,但这似乎不是正确的方法,因为我要检查大量的布尔值,所以必须有一些其他方法在一个线程上运行一个函数,回到runOnUiThread ()但我不知道如何使用它。这就是我在前提下所做的工作,但不是正确的编程。
private void startTest(View view){
tester = true;
}
@Override
public void run(){
if(tester){
for(TestButton b : buttons)
b.startAnimation();
tester = false;
}
root.postDelayed(this,1000);
}
---编辑2 --- This seems to work, and helped me out.如果其他人在将来需要这个。
答案 0 :(得分:0)
Following this guide,这似乎完美无缺。
public class TestButton extends Button{
private AnimatorSet as;
private Handler handler;
public TestButton(Context context, AttributeSet attrs){
super(context, attrs);
handler = new Handler(context.getMainLooper());
init();
}
private void init(){
//Does get called properly
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0.2f, 1.0f);
as = new AnimatorSet();
as.play(alphaAnimator);
as.setDuration(1000);
}
public void startAnimation(){
runOnUiThread(new Runnable(){
@Override
public void run(){
as.start();
}
});
as.start();
}
private void runOnUiThread(Runnable r){
handler.post(r);
}
}