[英]Android LayoutParams not being updated properly
所以我有一个滚动视图,我需要调整滚动视图的高度以确保它保持在模式弹出视图之上。 我不能使用约束布局,因为这个模式弹出视图不是同一个视图父级的子级。 所以我试图动态更新我的滚动视图布局参数,使其高度足够小,不会隐藏在模式弹出窗口后面。
弹出视图的高度可以在点上改变,所以我有一个回调,它可以随时返回模态视图的新高度。 在那个回调中,我像这样调整滚动视图的高度:
someModalView.onHeightChanged = { newViewHeight ->
Log.d("TESTHEIGHT", "PreHeight = ${scrollView.height}")
scrollView.layoutParams = FrameLayout.LayoutParams(scrollView.width, scrollView.height - newViewHeight)
scrollView.requestLayout()
Log.d("TESTHEIGHT", "PostHeight = ${scrollView.height}")
}
不幸的是,上面的代码似乎什么也没做,在我的日志中我可以看到 PreHeight 打印的高度与 PostHeight 相同。 视图高度没有改变的任何原因?
另外,我确实调试了它并确保 newViewHeight 不是 0,它不是,它是 ~800
最终通过向视图添加填充而不是像这样更改其高度来使其工作:
someModalView.onHeightChanged = { newViewHeight ->
scrollView.setPadding(0, 0, 0, newViewHeight)
}
这完全符合我的需要,但是它并不能真正回答问题,所以我将把它留在可能有帮助的其他人的答案中。 但是很高兴知道为什么更改布局参数不会更新视图高度。
试着看看它对你有用
val params = scrollView.layoutParams;
params.height = scrollView.height - newViewHeight
scrollView.layoutParams = params
一旦我需要获取软键盘的高度来更新我的视图:
public class MainActivity extends AppCompatActivity {
private ScrollView sView;
private int heightDiff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sView = findViewById(R.id.scrollView);
//Here we get the height of soft keyboard by observing changes of softKeyboard height.
sView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
heightDiff = sView.getRootView().getHeight() - sView.getHeight();
}
});
final EditText email = findViewById(R.id.eemail);
EditText firstName = findViewById(R.id.efirstname);
firstName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!isVisibleWhileSoftKeyboardShowing(email) && hasFocus) {
sView.postDelayed(new Runnable() {
@Override
public void run() {
sView.smoothScrollBy(0, 200);
}
}, 500);
}
}
});
}
/**
* check if a view is currently visible in the screen or not
*
* @param view
* @return
*/
public boolean isVisibleWhileSoftKeyboardShowing(final View view) {
if (view == null) {
return false;
}
if (!view.isShown()) {
return false;
}
final Rect actualPosition = new Rect();
view.getGlobalVisibleRect(actualPosition);
final Rect screen = new Rect(0, 0, getScreenWidth(), getScreenHeight() - heightDiff);
return actualPosition.intersect(screen);
}
/**
* to get screen width
*
* @return
*/
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
/**
* to get screen height
*
* @return
*/
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
heightDiff 是软键盘的高度。 有2个编辑文本。 如果softKeyboard隐藏了较低的,我想滚动。 希望这与您的情况相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.