Search code examples
androidviewpropertiestableviewcreation

When to read view's properties ( eg. widths) in activity?


I populate TableLayout in OnCreate(..) method. I'd like to get width of each column of the table. The problem is during OnCreate(...) method view has width set to 0. Where is correct place to collect table widths?

I also tried OnStart(...) (from doc "Called when the activity is becoming visible to the user.") but the result was the same.

simpler example shows the problem (differ from upper description):

package xliiv.hello;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class __helloworldActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (Button) findViewById(R.id.button1);
        int width = tv.getWidth();
        //this width will be 0! I expect that textview widths is not 0
        Log.i("tag", "" + width);
    }

Solution

  • You should do this in onWindowFocusChanged() , That will give the exact width

    Try this:

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
    
        int width = findViewById(R.id.button1).getWidth();
    
        Log.i("tag", "" + width);
    
    }