我的AsyncTask不能平滑地更新UI(动画)

时间:2013-11-12 02:17:30

标签: android android-asynctask android-animation android-ui

我想让TextView一点一点地出现,就像动画一样。问题是,动画不流畅。它有时会卡住一段时间,然后重新开始。有时甚至更糟,它会回来......我的意思是,TextView变得越来越大但突然变小然后再变大。谁能帮助我?

private class UnfoldTask extends AsyncTask<Integer, Integer, Integer> {

    View view;

    public UnfoldTask(View v) {
        this.view = v;
        ViewGroup.LayoutParams pa = view.getLayoutParams();
        pa.height = 0;
        view.setLayoutParams(pa);
    }

    @Override
    protected Integer doInBackground(Integer... maxHeight) {
        ViewGroup.LayoutParams pa = view.getLayoutParams();
        while (pa.height < maxHeight[0]) {
                pa.height += (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                sleep(100);
                publishProgress(pa.height);
        }
        return maxHeight[0];
    }

    private void sleep(int i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        ViewGroup.LayoutParams pa = view.getLayoutParams();
        pa.height = values[0];
        view.setLayoutParams(pa);
    }

    @Override
    protected void onPostExecute(Integer result) {
        ViewGroup.LayoutParams pa = view.getLayoutParams();
        pa.height = result;
        view.setLayoutParams(pa);
    }
}

2 个答案:

答案 0 :(得分:0)

你应该使用比例动画。这是一个例子:

ScaleAnimation animation = new ScaleAnimation(1, 2, 1, 2, centerX, centerY); // Scales from normal size (1) to double size (2). centerX/Y is the center of your text view. Change this to set the pivot point of your animation.
animation.setDuration(1000);
myTextView.startAnimation(animation);

答案 1 :(得分:0)

您可以使用droidQuery来简化此操作:

//this will set the height of myView to 0px.
$.with(myView).height(0);

//when you are ready to animate to height (in pixels):
$.with(myView).animate("{height:" + height + "}", new AnimationOptions());

如果您想获得想象力,请查看文档 - 例如添加持续时间和事件回调。如果您仍然注意到非平滑动画,请考虑将应用程序属性添加到 AndroidManifest

android:hardwareAccelerated="true"