Question

I have Fragment with onViewCreate method.

I'm creating there TableLayout with some rows and colums. I want to get height and width of single cell ( every cell has the same width and height ). However, when both cell.getHeight() and cell.getWidth() methods return 0. What's more when i used onPreDraw() method,

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 ?
}

thanks in advance for help!

Was it helpful?

Solution

  • because the last line

    Log.d(TAG, finalWidht + " " ); // returns still 0 ? WHY ?

will be executed before your ViewTreeObserver trigers it's global layout listener. ViewTreeObserver has it's own threads to measure the layout dimensions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top