我正在尝试通过使用界面和以下代码修改它的边距来移动 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/