How to make a simple square on Android?

1

Can you make a square full of color without all the complications? I say complications, because the examples I see here on the internet require that I create another class, inheriting from the View, doing drawRect() in the onDraw() function through Canvas ...

Finally, there is something so simple:

int width = 10;
GridLayout gl = (GridLayout)findViewById( R.ids.mainGridLayout );
Square s = new Square( width );
gl.addView( s );
    
asked by anonymous 11.02.2014 / 05:18

3 answers

3

As I think you want to add a square to a GridLayout , the simplest solution would be to create a View, set a background color, and include it in GridLayout :

View view = new View(this);
view.setBackgroundColor(Color.GREEN);
gl.addView(view);

But for your information Android allows you to create shapes, such as rectangles (and therefore squares), and include them as the background of a layout as if it were a drawable . With this your squares can have:

  • Custom color and thickness borders
  • Rounded edges
  • Background gradients (in the direction you want them)

For example:

res / drawable / my_retangulo.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <stroke
         android:width="2dp"
         android:color="#FFFFFFFF"/>
    <gradient
        android:startColor="#DD000000"
        android:endColor="#DD2ECCFA" 
        android:angle="225"/> 
     <corners 
        android:radius="2dp"
        android:bottomRightRadius="0dp"
        android:bottomLeftRadius="0dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp"/>
</shape>

You include in the layout like this:

<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/meu_retangulo" />
    
11.02.2014 / 11:25
1

If all you want is a square, why not just use a LinearLayout with a background color?

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

    <LinearLayout
        android:layout_centerInParent="true"
        android:background="@android:color/holo_red_dark"
        android:layout_width="200dp"
        android:layout_height="200dp" />

</RelativeLayout>

You can position it anywhere you want, even over other views.

    
11.02.2014 / 11:00
0

You can also create your image and use it as a Drawable feature.

    
05.01.2016 / 03:43