【发布时间】:2017-10-31 18:28:46
【问题描述】:
我有一个简单的类AppPopup,它扩展了 FrameLayout。该类膨胀其内容并将其存储在内容变量中。我需要内容位于弹出窗口视图的中心。为了测量内容,我覆盖了 onMeasure,但高度/在这个方法中内容的宽度等于-1
public class AppPopup extends FrameLayout {
private View content;
private View bg;
public AppPopup(@NonNull Context context) {
super(context);
}
public AppPopup(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public void setLayout(int resId) {
LayoutInflater li=LayoutInflater.from(getContext());
bg=li.inflate(R.layout.popup_bg_fade,null);
content=li.inflate(resId,null);
}
public void show() {
addView(bg);
addView(content);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
Log.d("layout",content.getLayoutParams().width+","+content.getLayoutParams().height+","+(content.getParent()==this)); -1,-1,true
content.setX(widthSize/2-content.getLayoutParams().width/2);
content.setY(heightSize/2-content.getLayoutParams().height/2);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Log.d("layout",content.getLayoutParams().width+","+content.getLayoutParams().height+","+(content.getParent()==this)); //-1,-1,true
}
}
我在父视图中调用它:
AppPopup popup=new AppPopup(this);
root.addView(popup);
popup.setLayout(R.layout.gameover_popup1);
popup.show();
在 onLayout 内大小也等于 -1。但我可以在屏幕上以正确的大小看到我的视图。 我知道我遗漏了一些简单的东西,但不知道是什么。
【问题讨论】:
标签: android measurement