Reputation: 369
I am having two text views in Linear layout having horizontal orientation. Width of text views are wrap_content. If the sum of width of two text views is less than the screen width it is fine. If the sum of width exceeds the screen width then i need to change the orientation from horizontal to vertical.
I tried using getWidth() in onCreate of the activity but it returned 0. I can try creating a custom view with onSizeChanged() function but i am using two text views so i am not sure that when onSizeChanged() in one text view will not make sure that the other textview is fully drawn to get the width. Any suggestions is really helpful for me.
<LinearLayout android:id="@+id/status_container"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView android:id="@+id/view1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView android:id="@+id/view2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
// In OnCreate() function
TextView view1 = (TextView) findViewById(R.id.view1);
TextView view2 = (TextView) findViewById(R.id.view2);
view1.setText("Good Morning,");
view2.setText("I am Ron");
int view1_width = view1.getWidth();
int view2_width = view2.getWidth();
if ((view1_width + view2_width) > screen_width) {
// Change the Linear Layout orientation to Vertical
}
Here view1_width and view2_width are returning 0. I want to check if the view1_width + view2_width is greater than the screen width then i need to change the orientation into vertical, or else Horizontal orientation is fine.
-Ron
Upvotes: 0
Views: 2059
Reputation: 31779
Add this to your activity's onCreate
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//You should be able to get the width and height over here.
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
Upvotes: 1