3

I have created a custom ViewGroup ReadPage, and in activity I use it

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    pager=(ReadPage)findViewById(R.id.readpage);
    pager.addArticle("...");
}

While the addArticle need the view's width and height

public void addArticle(String s){
        articles.add(new Article(s,getMeasuredWidth(),getMeasuredHeight()));
}

But the measurewidth and measureheight is 0 at that time. So I want to know at which state the view will be measured so I can get the right value it show in screen.

jfxu
  • 690
  • 1
  • 5
  • 15

3 Answers3

1

This answer probably gives you what you need: https://stackoverflow.com/a/1016941/213528

You would maybe use it like this:

private int WIDTH;
private int HEIGHT;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    WIDTH = size.x;
    HEIGHT = size.y;

    pager = (ReadPage)findViewById(R.id.readpage);
    pager.addArticle("...");
}

// ...

public void addArticle(String s){
    articles.add(new Article(s, WIDTH, HEIGHT));
}
Community
  • 1
  • 1
ehehhh
  • 1,066
  • 3
  • 16
  • 27
1

Use ViewTreeObserver

 viewToMeasure.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
              viewToMeasure.getViewTreeObserver().removeGlobalOnLayoutListener(this);
             /* you can get the view's height and width here 
                using  viewToMeasure.getWidth() and viewToMeasure.getHeight() 
             */                         
         }
  });      
Praveena
  • 6,340
  • 2
  • 40
  • 53
0

Views are measured sometimes later, during a "measure pass". When View structure changes (due to adding , removing, updating a view), a measure and then a layout pass runs that re-calculates the View sizes and locations.

For example, you can set text data to a TextView any time, but the View itself decides how to display it, when it is ready to display it. The text warp etc is calculated then, and not while setting the text.

You should design the View displaying the Article to be similar. You can provide the data, but let View process and display it further when its onSizeChanged() is called. Views can also employ addOnLayoutChangeListener() to know when layout has been done.

S.D.
  • 29,290
  • 3
  • 79
  • 130