gpt4 book ai didi

Android - createView 后的事件

转载 作者:搜寻专家 更新时间:2023-11-01 08:51:19 26 4
gpt4 key购买 nike

我想在绘制后获取布局的宽度高度

我的代码实际上是在createView()方法中调用的。但我想等到布局绘制完成后再执行这段代码:

Log.i(TAG, "Height: "+myButton.getHeight()+" - width : "+myButton.getWidth());
// result is Height: 0 - width : 0

onCreateView() 调用后是否启动了任何事件?

最佳答案

使用全局布局监听器对我来说一直很有效。它的优点是能够在布局发生变化时重新测量事物,例如如果某些内容设置为 View.GONE 或添加/删除了 subview 。

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

// inflate your main layout here (use RelativeLayout or whatever your root ViewGroup type is
LinearLayout mainLayout = (LinearLayout ) this.getLayoutInflater().inflate(R.layout.main, null);

// set a global layout listener which will be called when the layout pass is completed and the view is drawn
mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
//Remove the listener before proceeding
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}

// measure your views here
}
}
);

setContentView(mainLayout);

根据您的使用情况,您可能希望在使用完监听器后将其移除,如图所示。

关于Android - createView 后的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23128305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com