2017-07-21 12 views
1

ボーダーを追加するカスタムRelativeLayoutを作成します。ボーダーは表示されません。 バックグラウンドアトリビュートを追加すると、ボーダーが表示されます。バックグラウンドアトリビュートを削除すると、ボーダーが消えます。バックグラウンドアトリビュートなしでボーダーを表示したいと思います。 誰も私にこの問題の解決方法を教えてもらえますか?ここでカスタムRelativeLayoutボーダーが表示されない

RelativeLayoutについては

public class BorderRelativeLayout extends RelativeLayout { 

Paint paint; 
Rect rect; 

public BorderRelativeLayout(Context context) { 
    super(context); 
    init(); 
} 

public BorderRelativeLayout(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(); 
} 

public void init(){ 
    paint = new Paint(); 
    paint.setColor(Color.RED); 
    paint.setAntiAlias(true); 
    paint.setStyle(Paint.Style.STROKE); 
    paint.setStrokeWidth(20f); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    rect = new Rect(0,0,getWidth(),getHeight()); 
    canvas.drawRect(rect,paint); 
} 

}

+0

あなたのデザインをアップロードします。多分、レイアウトをカスタマイズするのではなく助けてくれるかもしれません。 –

答えて

1

...私のコードであるあなたは、背景を設定している場合を除き、onDraw()は呼び出されません。したがって、この方法で枠線を作成することはできません。

ただし、カスタムサブクラスを作成するよりもはるかに簡単にRelativeLayoutに境界線を追加できます。単にShapeDrawableをXMLで作成し、レイアウトに割り当てるだけです。

border.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 

    <stroke 
     android:width="5dp" 
     android:color="#f00"/> 

</shape> 

layout.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/border"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_margin="24dp" 
     android:textColor="#000" 
     android:textStyle="bold" 
     android:text="hello world"/> 

</RelativeLayout> 

enter image description here

+0

プログラムでShapeDrawableを作成し、実行時に色を変更できますか? –

+0

@ChanMyaeAungできます。詳細はこちらhttps://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.htmlこちら、https://developer.android.com/reference/android/graphics/drawable/shapes/Shape.html –

関連する問題