0

我有带有 onViewCreate 方法的片段。

我正在用一些行和列创建 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 ?
}

提前感谢您的帮助!

4

1 回答 1

0
  • 因为最后一行

    Log.d(TAG, finalWidht + " " ); // 仍然返回 0 ? 为什么 ?

将在您的 ViewTreeObserver 触发它的全局布局侦听器之前执行。ViewTreeObserver 有自己的线程来测量布局尺寸。

于 2013-08-20T15:54:09.150 回答