Android: cómo dibujar un borde a un LinearLayout


Tengo tres archivos. El XML, la función draw y la Actividad principal. Tengo algo de LinearLayout en mi archivo XML.

<LinearLayout android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:layout_weight="1">
    <LinearLayout android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  android:background="#ef3"
                  android:id="@+id/img01"/>
    <LinearLayout android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  android:background="#E8A2B4"
                  android:id="@+id/img02"/>
</LinearLayout>

Esta es la función draw:

public class getBorder extends TextView {
    public getBorder(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();

        paint.setColor(android.graphics.Color.RED);

        canvas.drawLine(0, 0, this.getWidth() - 1, 0, paint);
        canvas.drawLine(0, 0, 0, this.getHeight() - 1, paint);
        canvas.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1,
            this.getHeight() - 1, paint);
        canvas.drawLine(0, this.getHeight() - 1, this.getWidth() - 1,
            this.getHeight() - 1, paint);
    }
}

Y esta es la actividad principal:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final getBorder getBorder = new getBorder(this);
    final LinearLayout img01 = (LinearLayout) findViewById(R.id.img01);
    img01.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            getBorder.setWidth(100);
            getBorder.setHeight(100);
            img01.addView(getBorder);
        }
    });       
}

El programa podía dibujar el borde pero el tamaño no encajaba con el LinearLayout. Y cuando hago clic en el LinearLayout de nuevo, el programa se bloquea.

Otra cosa, quiero dibujar dos círculos en el centro de la LinearLayout, pero ¿cómo podría averiguar las coordenadas del centro?

Author: Massimiliano Kraus, 2011-11-20

2 answers

¿Realmente necesitas hacer eso programáticamente?

Sólo teniendo en cuenta el título: Usted podría utilizar un ShapeDrawable como android: fondo {

Por ejemplo, definamos res/drawable/my_custom_background.xml como:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

Y define android:background="@drawable/my_custom_background".

No he probado pero debería funcionar.

Actualización:

Creo que es mejor aprovechar el poder de recursos xml shape drawable si se ajusta a sus necesidades. Con un " desde cero" project (para android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

Y a res/drawable/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="5dip"
        android:color="@android:color/white" />
</shape>

Informó que funciona en un dispositivo de pan de jengibre. Tenga en cuenta que necesitará relacionar android:padding del LinearLayout con el valor de android:width shape/stroke. Por favor, no utilice @android:color/white en su aplicación final, sino un color definido por el proyecto.

Usted podría aplicar android:background="@drawable/border" android:padding="10dip" a cada uno de los LinealLayout de su muestra proporcionada.

En cuanto a sus otros mensajes relacionados con mostrar algunos círculos como Fondo de LinearLayout, estoy jugando con Inset/Scale/Layer drawable resources ( consulte Drawable Resources para obtener más información) para obtener algo que funcione para mostrar círculos perfectos en el fondo de un LinearLayout pero falló en este momento {

Su problema reside claramente en el uso de getBorder.set{Width,Height}(100);. ¿Por qué haces eso en un método onClick?

Necesito más información para no perder el punto: ¿por qué haces eso programáticamente? ¿Necesitas un comportamiento dinámico? Su los elementos de diseño de entrada son png o ShapeDrawable es aceptable? sucesivamente.

Continuará (tal vez mañana y tan pronto como proporcione más precisiones sobre lo que desea lograr) {

 386
Author: Renaud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 07:26:14

Extienda LinearLayout / RelativeLayout y utilícelo directamente en el XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>
 15
Author: Gabriel Riba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-03 10:57:55