【问题标题】:setLayoutParams doesn't work second timesetLayoutParams 第二次不起作用
【发布时间】:2014-01-31 22:29:49
【问题描述】:

我编写了以下代码,首先增加 ImageView 的大小,然后在 100 毫秒后减小同一个 ImageView 的大小。然而,这段代码增加了 ImageView 的大小,但不会减小它的大小,或者延迟 100 毫秒后的代码不会影响 imageView 的尺寸。

我做错了什么?

uiHandler.post(new Runnable()
{
    @Override
    public void run()
    {
        FrameLayout.LayoutParams layout = (android.widget.FrameLayout.LayoutParams) imageView.getLayoutParams();
        layout.height = (int) (2*iconsSizeInDP);
        layout.width = (int) (2*iconsSizeInDP);
        imageView.setLayoutParams(layout);
        try
        {
            Thread.sleep(50);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
        // following code block doesnt'affect imageView dimensions
        layout.height = (int) iconsSizeInDP;
        layout.width = (int) iconsSizeInDP;
        imageView.setLayoutParams(layout);
    }
});

问候

【问题讨论】:

  • 尝试在您说代码不起作用的地方再次创建LayoutParams FrameLayout.LayoutParams layout = (android.widget.FrameLayout.LayoutParams) imageView.getLayoutParams();。还要增加Thread.sleep() 的时间。可能很难看出差异。
  • 当你一直用睡眠阻塞UI线程时,你认为重新布局发生在哪个线程?
  • 你确定没有调用第二个 Set 吗?请使用AsyncTask 而不是uiHandler 并再次测试。复制onPreExecute() 中的第一部分在onBackground 中休眠并在onPostExeute() 中设置第二个参数

标签: java android view layoutparams


【解决方案1】:

请在线查看FrameLayout.LayoutParams layout = (android.widget.FrameLayout.LayoutParams) imageView.getLayoutParams();

请在尝试使FrameLayout.LayoutParams layout全局化时看看

【讨论】:

    【解决方案2】:

    您在同一个 UI 线程中更改了 2 次布局,因此只有最后一次更改才能生效。 您应该分离到 2 个 UI 线程,如下所示:

    uiHandler.post(new Runnable()
    {
        @Override
        public void run()
        {
            FrameLayout.LayoutParams layout = (android.widget.FrameLayout.LayoutParams) imageView.getLayoutParams();
            layout.height = (int) (2*iconsSizeInDP);
            layout.width = (int) (2*iconsSizeInDP);
            imageView.setLayoutParams(layout);
        }
    };
    uiHandler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
            // following code block doesnt'affect imageView dimensions
            layout.height = (int) iconsSizeInDP;
            layout.width = (int) iconsSizeInDP;
            imageView.setLayoutParams(layout);
        }
    },50);
    

    【讨论】:

    • 好的。剩下的唯一问题是当用户将手指放在 imageView 上时,imageView 会多次调整大小。关于如何解决它的任何想法?
    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2015-06-21
    • 2011-10-04
    • 1970-01-01
    • 2020-04-16
    • 2011-11-10
    • 2019-11-25
    相关资源
    最近更新 更多