【发布时间】:2013-11-06 18:05:24
【问题描述】:
我有一个TextView 包含在HorizontalScrollView 中,并且我希望文本在不可滚动时居中,但是当文本足够大以使其HorizontalScrollView 容器可滚动时,我需要更改重力TextView 中的 Gravity.LEFT。如果我不这样做并保持重心居中,HorizontalScrollView 将显示错误的文本,因为它会切断大部分文本,如果文本保持居中,最后会有空白区域。这是我当前处理此问题的代码:
//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);
}
});
我的函数canScroll() 工作正常,因为它在 Toast 中正确更新,所以这不是问题。问题是,一旦调用 setLayoutParams(),我觉得 TextView 需要“刷新”。这是因为当第一个数字添加到使其可滚动的TextView 时,Toast 返回它现在可滚动但重力保持居中,因此当向左滚动时数字的第一部分被剪切,如下所示:
然而,每当添加下一个数字时,它会正确更新,重力设置为 Gravity.LEFT,因此滚动中的任何文本都不会被截断看法。如何正确更新 TextView 重力使其立即发生? 我已经尝试在 setLayoutParams() 之后添加 toNumber.invalidate() 和 toTextScrollView.invalidate() 但它仍然不会按时更新。
这里是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>
【问题讨论】: