I have a TextView
contained in a HorizontalScrollView
, and I want the text to be centered whenever not scrollable, but when the text is big enough to make its HorizontalScrollView
container scrollable, I need to change the gravity of the TextView
to be Gravity.LEFT
. If I do not do this and keep the gravity centered, the HorizontalScrollView
will show the text wrong, as in it will cut off most of the text, and there will be empty space at the end if the text remains centered. Here is my current code to handle this:
//make horizontal scroll text center and work
final HorizontalScrollView toTextScrollView = (HorizontalScrollView)parentView.findViewById(R.id.horizScroll);
toTextScrollView.addOnLayoutChangeListener(new OnLayoutChangeListener(){
@Override
public void onLayoutChange(View v, int left, int top,
int right, int bottom, int oldLeft, int oldTop,
int oldRight, int oldBottom) {
//if scrollable, change toNumber layout_gravity to left, else keep it at center
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if(canScroll(toTextScrollView))
params.gravity=Gravity.LEFT;
else
params.gravity=Gravity.CENTER;
Toast.makeText(getActivity(), "Can scroll: " + canScroll(toTextScrollView), Toast.LENGTH_LONG).show();
toNumber.setLayoutParams(params);
}
});
My function canScroll()
works properly as it updates in the Toast correctly, so that is not the issue. The issue is that I feel the TextView
needs to "refresh" once setLayoutParams() is called. This is because when the first number is added to the TextView
that makes it scrollable, the Toast returns it is now scrollable but the Gravity remains centered and therefore the first part of the number is cut of when scrolling left, like this:
However, whenever the next number is added it updates properly, the gravity is set to Gravity.LEFT, and therefore none of the text is cut off in the scroll view. How do I properly update the TextView gravity so it happens instantly? I have tried adding toNumber.invalidate() and toTextScrollView.invalidate() right after setLayoutParams() but it still won't update on time.
Here is the TextView
:
<HorizontalScrollView
android:id="@+id/horizScroll"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_gravity="center"
>
<TextView
android:id="@+id/toField"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="35sp"
android:singleLine="true"
android:textColor="@color/lightblue"
android:layout_gravity="center"
android:scrollHorizontally="true"
android:focusable="true"
android:freezesText="true"/>
</HorizontalScrollView>