安卓。在运行时更改 LinearLayout 的边距

标签 android android-linearlayout margin

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

        @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;
    }

代码与第一次调用一起工作——当 Activity 被创建时。但是无论何时调用代码块, View 都不会发生任何变化。我可以确认 margin 参数确实被改变了,因为三个事实: 1)代码在启动时有效 2)记录 marginTop 值总是给出新值(正在更改) 3) 在层次结构 View 中我可以看到新的 margin 值

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

最佳答案

试试这个:

@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();
        }
    });

}

关于安卓。在运行时更改 LinearLayout 的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320856/

相关文章:

android - fragment 之间动画的共享元素

android - 在单独的 Activity 中显示绘制的 AChartEngine 图

html - 图片没有响应式边距底部

html - IE 中的边距不起作用

Android - 改变 margin 问题?

android - 在 API 16 及更低版本中完全删除复选框的正确方法

java - 如何通过 Intent 传递对象列表

Android 文件上传崩溃问题

android - LinearLayout 中的 Edittext 在滚动背景时闪烁

Android - Relativelayout 中的 ScrollView 中的 LinearLayout