2016-06-18 14 views
0

我有一個TextView的子類,並希望繪製一個水平線,使其高度爲1px。沒關係,但我也想通過將頂部邊距設置爲高度的一半來使其垂直居中。 但事實證明,這是失敗的。 任何解決方案? 謝謝如何找到一個android textview的中點

 LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1); 
     int h = getHeight(); 
     lp.setMargins(0, h/2, 0, 0); 
+0

基本上,如果你只是想畫一條水平線,爲什麼不在你的xml中做呢? –

+0

@ A.Omar你能告訴他,如何通過任何代碼與XML? –

+0

如果您打算使用刪除線效果,請考慮使用「StrikethroughSpan」。 – Richard

回答

0

您可以在XML做到這一點:

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Hello World!.\nA second line test."/> 

    <View 
     android:layout_width="match_parent" 
     android:layout_height="1dp" 
     android:background="@android:color/darker_gray" 
     android:layout_centerVertical="true"/> 
</RelativeLayout> 

問候。

0

如果你來這裏的一些截圖你想做什麼,我可以幫你輕鬆。但我可以建議你使用FrameLayout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <View 
     android:layout_width="match_parent" 
     android:layout_height="1dp" 
     android:layout_gravity="center" 
     android:background="#123456" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:text="Horizontal Line" /> 

</FrameLayout> 

有一個指南FrameLayout這裏:Frame Layout

,然後將截圖:

enter image description here

0

沒有XML你可以覆蓋onDraw(Canvas canvas)和借鑑在你的子類文本視圖中的行如下所示:

public final class TextViewEx extends TextView 
{ 
    private final Paint mPaint = new Paint(); 

    protected final void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 

     mPaint.setStyle(Paint.Style.STROKE); 
     mPaint.setStrokeWidth(1); 
     mPaint.setColor(Color.GRAY); 

     float y = getHeight()/2f; 

     canvas.drawLine(0, y, getWidth(), y, mPaint); 
    } 
} 
相關問題