【问题标题】:Android. Change margin of LinearLayout on runtime安卓。在运行时更改 LinearLayout 的边距
【发布时间】:2015-10-25 03:24:36
【问题描述】:

我正在尝试通过使用界面和以下代码修改其边距来移动 LinearLayout 视图:

        @Override
public void onListScroll(int offset) {
        tabBarOffset += offset;
        if (tabBarOffset < 0) tabBarOffset = 0;
        if (tabBarOffset > 50) tabBarOffset = 50;
        View tabBar = findViewById(R.id.movingTabBar);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tabBar.getLayoutParams();
        params.topMargin = tabBarOffset;
    }

代码适用于第一次调用——当活动创建时。但是无论何时调用代码块,视图都不会发生变化。由于三个事实,我可以确认 margin 参数确实被改变了: 1)代码在启动时起作用 2)记录 marginTop 值总是给出新值(它正在被改变) 3) 在层次视图中我可以看到新的边距值

所以我想我只需要调用一些方法来更新视图本身吗?让它重绘? 或者我可能必须在 UI 线程上调用一些代码?因为这段代码是从接口回调中运行的。

【问题讨论】:

    标签: android android-linearlayout margin


    【解决方案1】:

    试试这个:

    @Override
    public void onListScroll(final int offset) {
    
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                tabBarOffset += offset;
                if (tabBarOffset < 0) tabBarOffset = 0;
                if (tabBarOffset > 50) tabBarOffset = 50;
                ViewGroup tabBar = findViewById(R.id.movingTabBar);
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tabBar.getLayoutParams();
                params.topMargin = tabBarOffset;
                tabBar.requestLayout();
            }
        });
    
    }
    

    【讨论】:

    • 感谢您的帮助。遗憾的是,这没有任何效果。
    • 只是为了兴趣,请尝试编辑的变体
    • 虽然可行,但计算结果并不便宜。我想我将不得不在一天结束时使用 simpe TranslateY 和 TranslatY。尝试通过移动 topBar 来实现滚动视图。无论如何都会将答案标记为正确。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 2013-11-01
    • 2018-08-10
    • 2013-09-02
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多