【发布时间】:2013-05-13 16:13:10
【问题描述】:
我想在我的自定义线性布局中添加新的 textView。但是在绘制线性布局之前,我想检查它是否仍然适合而不与右侧的按钮重叠,如果它会重叠,我想在绘制之前在我的 textView 中剪切文本。
我的布局
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="60dp" >
<ImageButton
android:id="@+id/b_settings"
android:layout_width="50dp"
android:layout_height="44dp"
android:layout_alignParentRight="true"
android:layout_margin="0dp"
android:src="@drawable/watch_settings2x" />
<Button
android:id="@+id/b_test"
android:layout_width="50dp"
android:layout_height="44dp"
android:layout_toLeftOf="@id/b_settings"
/>
<com.client.views.Breadcrump
android:id="@+id/ll_breadcrump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="horizontal" />
</RelativeLayout>
我的流程看起来像这样,首先我将一个新的 TextView 添加到我的自定义视图中。
this.addView(TextView, position);
我已经实现了以下GlobalLayoutListener,它在自定义视图被绘制之前被调用,但宽度已经可用:
@Override
public void onGlobalLayout() {
cutBreadcrump();
}
然后我首先为我的面包屑(自定义视图)获取可用空间
int fragmentWidth = getView().getWidth();
int widthButtons = mIBSettings.getWidth() + mBTest.getWidth();
int spaceBreadcrump = fragmentWidth - widthButtons;
接下来我从我新添加的 TextView 中剪切字符并检查新的宽度
CharSequence text = textView.get(0).getText();
text = text.subSequence(0, text.length() - 1);
textView.get(0).setText(text);
但这是我的问题。更改文本后宽度不会改变。
mElements.get(0).getWidth();
我还尝试了paint.measureText(string); 方法来获取我的 TextView 的宽度,但它总是很长。也许这种方法的作用与我的预期不同......
所以我的问题简而言之是如何在绘制视图之前更改其文本后获取视图的新宽度
【问题讨论】:
-
使用
view.getLocationInWindow(int[] coords)应该可以让您查看这些视图是否重叠。 -
在屏幕上绘制视图之前检查它会更好吗?
-
您不能这样做,如果视图尚未在屏幕上绘制,则没有坐标。当您添加视图时,在视图上发布
Runnable,您将使用上述方法在其中检索坐标。 -
但我可以得到屏幕的宽度并减去其他元素。所以我看到我的自定义视图有多少空间。在我将我的新文本视图添加到我的布局之前,我可以检查所有文本视图是否适合?
-
所以你试着照你说的做?