【问题标题】:Android getWidth in Fragment returns 0Fragment中的Android getWidth返回0
【发布时间】:2013-08-20 23:54:09
【问题描述】:

我有带有 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 ?
}

提前感谢您的帮助!

【问题讨论】:

    标签: android view width fragment zero


    【解决方案1】:
    • 因为最后一行

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

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

    【讨论】:

    • 正确的代码取决于你要在哪里使用单元格的宽度和高度。当 onGlobalLayout 被调用时,你可以使用自己的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2014-03-02
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多