Search code examples
javaandroidvectorshapesrectangles

Android draw stripes of different height in a view


I'm using Java, Android studio. In a view, I need to programmatically create a random number of stripes of different colours and height as a % of the parent view height on the screen. No charts. Only a single column of stacked striped with varying heights. How can I achieve this? This is as complex as it will ever get, no complicated libraries required.

Image: Stacked horizontal stripes of varying colour and height

I spent 6 hours searching for a solution already, please help.


Solution

  • If you do not want to give yourself a hard time, You'd rather use a layout (ViewGroup) instead of a View.

    All you have to do is get yourself a randomizer (PRNG) and get yourself some colors.

    After that you can start inflating the layout with some views.

    final LinearLayout layout=(LinearLayout)findViewByid(R.id.YOUR_LINEARLAYOUT);
    layout.setOrientation(LinearLayout.VERTICAL);
    final Random rand=new Random();
    for(int i=0;i<3;i++){
      final LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
      p.weight=(float)Math.random();
      final TextView view=new TextView(this); //No listeners here!
      view.setLayoutParams(p);
      layout.addView(view);
      view.setBackground(new ColorDrawable(
        Color.rgb(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))
      ));
    }
    final LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(-1, 0);
    final TextView view=new TextView(this);
    view.setLayoutParams(p);
    layout.addView(view);
    view.setBackground(new ColorDrawable(
      Color.rgb(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))
    ));