2017-07-21 3 views
1

Je crée un RelativeLayout personnalisé pour ajouter une bordure. Mais la bordure n'apparaît pas. Lorsque j'ajoute un attribut d'arrière-plan, la bordure apparaît. Lorsque je supprime des attributs d'arrière-plan, la bordure disparaît. Je souhaite afficher une bordure sans attribut d'arrière-plan. Quelqu'un peut-il m'expliquer comment résoudre ce problème.Bordure RelativeLayout personnalisée non affichée

Voici mon code ...

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

télécharger votre conception. Peut-être que je peux vous aider au lieu de personnaliser une mise en page? –

Répondre

1

Pour RelativeLayout, onDraw() n'est pas appelé sauf si vous avez un ensemble d'arrière-plan. Vous ne pouvez donc pas créer une bordure de cette manière.

Cependant, vous pouvez ajouter une bordure à votre RelativeLayout beaucoup plus facilement qu'en créant une sous-classe personnalisée. Créez simplement un ShapeDrawable en XML et assignez-le à votre mise en page.

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

Puis-je créer ShapeDrawable par programme et changer de couleur à l'exécution? –

+0

@ChanMyaeAung Vous pouvez. Lire la suite ici https://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.html et ici https://developer.android.com/reference/android/graphics/drawable/shapes/Shape.html –