强制刷新/重绘Android布局?

7
我想改变布局的位置,并在 75 毫秒后将其返回到第一个位置以进行移动,以下是我的代码:
for(int i = 0; i < l1.getChildCount(); i++) {  
    linear = (LinearLayout) findViewById(l1.getChildAt(i).getId());  
    LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);  
    params.bottomMargin = 10;  
    linear.setLayoutParams(params);  
    SystemClock.sleep(75);
}   

问题在于应用程序停止了750毫秒,并且没有做任何事情。我尝试了invalidate()refreshDrawableState()requestLayout()postInvalidate(),并尝试调用onResume()onRestart()onPause()

4个回答

22

也许你需要:

linear.invalidate();
linear.requestLayout();

在进行布局更改之后。

编辑:

在不同的线程上运行代码:

new Thread() {
    @Override
    public void run() {
        <your code here>
    }
}.start();

每当您需要从该线程更新UI时,请使用以下内容:

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        <code to change UI>
    }
});

这段代码放在哪里?如果您在UI线程上运行此代码,则应用程序将停止,并且可能没有任何结果。请更具体地提出您的问题,同时不要更改问题,除非使用“EDIT:”标记。 - prc
感谢您的快速回复,很抱歉因为我是新手,关于代码它可以工作但是没有显示结果,所有布局在750毫秒后同时出现,而且我没有使用线程,谢谢。 - Youssef Maouche
然后,您需要在单独的线程中运行此代码,并在需要更新UI时使用runOnUIThread()。 - prc

2

经过数小时的测试,我找到了有关更新视图的解决方案,如果您对这些视图进行操作,例如添加子项、可见性、旋转等,则需要更新视图。

我们需要使用以下方法强制更新视图。

linearSliderDots.post {
        // here linearSliderDots is a linear layout &
        // I made add & remove view option on runtime
        linearSliderDots.invalidate()
        linearSliderDots.requestLayout()
    }

0
你应该尝试使用ValueAnimator(或对象动画器),以下代码是Kotlin的,但是相同的逻辑也适用于Java:
val childCount = someView.childCount
    val animators = mutableListOf<ValueAnimator>()
    for (i in 0..childCount) {
        val child = (someView.getChildAt(i))
        val animator = ValueAnimator.ofInt(0, 75)
        animator.addUpdateListener {
            val curValue = it.animatedValue as Int
            (child.layoutParams as ViewGroup.MarginLayoutParams).bottomMargin = curValue
            child.requestLayout()
        }
        animator.duration = 75
        animator.startDelay = 75L * i
        animators.add(animator)
    }
    animators.forEach { animator ->
        animator.start()
    }

基本上,您需要创建一堆动画师,其启动延迟与子元素数量成比例,因此一旦一个动画结束,新动画就会开始。


-1
ActivityName.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        <code to change UI>
    }
});

我不明白这如何回答问题。您能否解释一下它如何回答这个问题? - Alex.F

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接