[英]Android: Can I change the height of a view before it's drawn?
I'd like to do something like the following: 我想做以下事情:
rootLayout.getLayoutParams().height = 100;
Currently I have this line in my 'loadData' method. 目前,我的“ loadData”方法中包含此行。 The problem is - 'layoutParams' seems to be null until sometime after 'loadData' has been called (but before it is displayed obviously). 问题是-“ layoutParams”似乎为空,直到调用了“ loadData”之后的某个时间(但是在明显显示之前)。
Is there somewhere I can place this line where the layoutParams will have been instantiated, but still be before the view is shown for the first time? 有什么地方可以放置此行的位置,该行将实例化layoutParams,但仍在第一次显示视图之前?
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
rootLayout.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
rootLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
rootLayout.getLayoutParams().height = 100;
rootLayout.requestLayout();
}
});
You should consider to set layoutParams of this view as 您应该考虑将此视图的layoutParams设置为
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 100));
rootLayout.setLayoutParams(lp);
So You can set layoutParams height as 100 and assuming that your parent view as linear layout
,if it's not, then you should use its layoutparams 因此,您可以将layoutParams的高度设置为100,并假设您的父视图为linear layout
,否则请使用其layoutparams
on the docs you can check all the callbacks the view have that you can override https://developer.android.com/reference/android/view/View.html 在文档上,您可以检查视图中所有的回调,您可以覆盖https://developer.android.com/reference/android/view/View.html
if your view is inside an XML layout with the LayoutParams specified in there, you can/should put your code inside onFinishInflate 如果您的视图位于其中指定了LayoutParams的XML布局内,则可以/应该将代码放在onFinishInflate中
@Override
public void onFinishInflate() {
}
if you're doing all this programmatically, you can override the layout pass 如果您以编程方式执行所有操作,则可以覆盖版式传递
@Override
public void onLayout (boolean changed, int left, int top, int right, int bottom){
// be carefull that this get's called several times
}
alternatively (a nicer approach in my opinion), you can trick the onMeasure
of your view to have the size you want. 或者(我认为这是一种更好的方法),您可以欺骗视图的onMeasure
使其具有所需的大小。 For example, to have a view with a maxWidth
例如,要使视图具有maxWidth
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// apply max width
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
if (maxWidth > 0 && maxWidth < measuredWidth) {
int measureMode = MeasureSpec.getMode(widthMeasureSpec);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth, measureMode);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.