-1

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.

Cerberus
  • 9
  • 3

1 Answers1

0

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))
));
JumperBot_
  • 551
  • 1
  • 6
  • 19
  • Thank you so much! Didn't work immediately for me, but was perfect after changing from LinearLayout.MATCH_PARENT to LinearLayout.LayoutParams.MATCH_PARENT and casting Math.random() to float. – Cerberus Jul 31 '22 at 12:38
  • @Cerberus What tiny change was it? I suspect that it was about the PRNG generating an unusual ratio for the `weight` attribute. – JumperBot_ Jul 31 '22 at 12:39
  • I just edited the comment I thought pressing enter would let me make new lines. – Cerberus Jul 31 '22 at 12:40
  • @Cerberus Oh I see now, I might have looked too much on the AOSP to get dizzy about the variables, I'll edit the answer for the future viewers! – JumperBot_ Jul 31 '22 at 12:41