我在onViewCreate方法中使用Fragment。
我正在使用一些行和列创建TableLayout。 我想获得单个单元格的高度和宽度(每个单元格具有相同的宽度和高度)。 但是,当cell.getHeight()和cell.getWidth()方法都返回0.当我使用onPreDraw()方法时,还有更多,
private TextView cell
private int finalHeight;
private int finalWidth;
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
Context contextThemeWrapper = new ContextThemeWrapper( getActivity(), android.R.style.Theme_Holo_Light );
LayoutInflater localInflater = inflater.cloneInContext( contextThemeWrapper );
View thisView = localInflater.inflate( R.layout.fragment_wizard_table, container, false );
final TableLayout table = new TableLayout( App.getAppContext() );
for (hoursIter = 0; hoursIter < hours.length; hoursIter++) {
TableRow row = new TableRow( App.getAppContext() );
for (daysIter = 0; daysIter < initDays().length; daysIter++) {
cell = new TextView( App.getAppContext() )
// cell.getWidth() here return 0;
}
}
// cell.getWidth() here still returns 0 ;
cell.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
cell.getViewTreeObserver().removeGlobalOnLayoutListener(this);
finalWidth = cell.getWidth(); // it's ok here ( work )
finalHeight = cell.getHeight(); // it's ok here (works)
}
});
// BUT NOW:
Log.d(TAG, finalWidht + " " ); // returns still 0 ? WHY ?
}
提前感谢您的帮助!
答案 0 :(得分:0)
因为最后一行
Log.d(TAG,finalWidht +“”); //还是0?为什么?
将在ViewTreeObserver将其全局布局侦听器分组之前执行。 ViewTreeObserver有自己的线程来测量布局尺寸。